考虑这个例子:
class Parent<T> implements MyInterface<T> {...}
class Child1 extends Parent<ConcreteType1>{...}
class Child2 extends Parent<ConcreteType2>{...}
然后是以下工厂:
public class Factory<T> {
public static <T> Parent<T> getChild(Type type) {
switch (type) {
case value1:
return new Child1();
case value2:
return new Child2();
}
}
}
Type
参数只是一个 enum
.
现在,
- 如果我保留上述内容,则会收到以下错误:无法转换
Child1
至Parent<T>
- 如果我删除泛型,只留下
Parent
而不是Parent<T>
,我收到警告
如何解决这个问题?
最佳答案
该方法并不真正知道 T
的确切类型,所以你可以返回 Parent<?>
:
public static Parent<?> getChild(Type type) {
...
}
或者,您可以扩展 Type
类来实际构造子级,这样您就可以控制确切的输出:
public static <T> Parent<T> getChild(Type<T> type) {
return type.createChild();
}
关于java - Java 中的泛型 + 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35267006/