如何在Java中覆盖通用列表返回类型 [英] How to override generic list return type in java
问题描述
我正在尝试重写将类型返回为子类列表的方法,如下例所示,由于泛型问题,我无法在我的子类中做到这一点.我无法更改我的超类代码,那么如何解决该问题?任何人都可以指导我...在此先感谢.
I am trying to override the method which return type as list in sub class like as below example, due to generics issue i can not able to do it in my sub class. I can not able to change my super class code, so how i can resolve the issue? any one can please guide me...many thanks in advance.
无法更新的超级类:
public class Animal {
private String legs;
}
public class TestSuper {
public List<Animal> addAnimals() {
return animals;
}
}
子类:
public class Dog extends Animal {
private String sound;
}
public class TestSub extends TestSuper {
public List<Dog> addAnimals() { --> I need to override this method but want return type as List of dogs
return null;
}
}
推荐答案
如果真的无法更新超级类,恐怕您根本无法更新.
If the super classes really can't be updated, I'm afraid you simply can't.
如果您能够更新超级类:
在 TestSuper
中,您将使用 public List< ;?扩展Animal>addAnimals()
而不是 public List< Animal>addAnimals()
.
In TestSuper
, you would have use public List<? extends Animal> addAnimals()
instead of public List<Animal> addAnimals()
.
您还有什么其他解决方案:
您可以使用这样的实用程序方法:
You could use such a utility method:
@SuppressWarnings("unchecked")
public static <T extends Animal> List<T> cast(List<Animal> animals, Class<T> subclass) {
List<T> out = new ArrayList<T>();
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<Dog> dogs = TheClassNameYouChose.cast(animals, Dog.class);
这篇关于如何在Java中覆盖通用列表返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!