【发布时间】:2021-09-28 22:18:17
【问题描述】:
Java 编译器的这种行为让我有点不知所措。有人可以解释为什么会这样吗?考虑这个例子:
public static abstract class GenericClass<A extends GenericClass<A>> {
protected abstract void method();
protected <B> B getB(Class<B> bclass) {
return null;
}
}
// ...
GenericClass<?> gc = new GenericClass() {
@Override
protected void method() {
String s = getB(String.class); // does not compile
}
};
String s = gc.getB(String.class); // compiles
由于new 中没有给出泛型参数,匿名类继承自原始类型GenericClass。即使方法getB 没有提及A,通用信息仍然丢失并且方法调用无法编译。为什么会这样?
此外,我无法为new 指定泛型参数的原因是因为它应该是匿名类本身,但我无法命名匿名类来传递它。我该如何正确地做到这一点?
【问题讨论】:
标签: java generics anonymous-class raw-types