【发布时间】:2011-04-05 21:15:32
【问题描述】:
我定义了以下类
public class AbstractManager<E> {
public E save(E o) {
// Implementation omitted
}
public <T> T getSingleResult(Query query, Class<T> clazz) {
return clazz.cast(query.getSingleResult());
}
}
public class MatchingAlgorithmManagerImpl extends AbstractManager {
void someMethod() {
// compiler error: "Type mismatch: cannot convert from Object to Country"
Country c = this.getSingleResult(query, Country.class);
}
}
我很困惑为什么会出现这个编译器错误,当然它应该使用Country 作为<T> 的值,而它似乎使用Object,我认为这是默认值<E> 当我没有指定参数类型时。
更奇怪的是,如果我将子类定义更改为public class MatchingAlgorithmManagerImpl extends AbstractManager<Object>,错误就会消失。
为什么我为E 定义的类型有任何相关性?
【问题讨论】:
-
query.getSingleResult() 返回什么?你没有看到 ClassCastException,对吧?
-
它返回一个对象,但我将它动态转换为
<T> -
啊,是的,你也写了它不能编译,并不是说它在运行时失败......
-
确实编译失败,为什么你认为它在运行时会失败?
-
如果你给 clazz.cast 提供了错误的类型,它会在运行时失败。但是当然,它只能在编译后在运行时失败;)