如果超级班真的无法更新,我恐怕你根本就不能.
如果您能够更新超类:
在TestSuper中,您将使用公共列表 addAnimals()而不是public List< Animal> addAnimals().
你有什么其他解决方案:
您可以使用这样的实用方法:
@SuppressWarnings("unchecked")
public static List cast(List animals,Class subclass) {
List out = new ArrayList();
for (Animal animal : animals) {
if (!subclass.isAssignableFrom(animal.getClass())) {
// the "animal" entry isn't an instance of "subclass"
// manage this case however you want ;)
} else {
out.add((T) animal);
}
}
return out;
}
然后,打电话:
List dogs = TheClassNameYouChose.cast(animals,Dog.class);