【发布时间】:2011-12-22 17:48:18
【问题描述】:
上周四,工作人员向我展示了一个编译错误,我无法以干净的方式修复它,此后一直困扰着我。
问题与泛型有关,我重构了生成编译错误的代码的简化版本。错误发生在下面显示的最后一行代码中。
我一直在寻找整个互联网,但似乎找不到一个体面的解释为什么 Java 编译器不接受代码。我想如果允许代码,可能会在 Bar.operationOnBar() 中创建一个类转换问题,但我不知道如何。
有人可以告诉我为什么这不能编译吗?
public interface Interface {
}
public class Type implements Interface {
}
public class Bar<T> {
public Bar(Class<T> clazz) {
}
public void operationOnBar(Class<T> arg){
}
}
public class Foo {
public <T> Bar<T> bar(Class<T> clazz){
return new Bar<T>(clazz);
}
public static void main(String[] args) {
Class<? extends Interface> extendsInterfaceClazz = Type.class;
new Foo().bar(extendsInterfaceClazz).operationOnBar(Type.class);
}
}
Foo.main()第二行编译报错:
The method operationOnBar(Class<capture#1-of ? extends Interface>) in the type Bar<capture#1-of ? extends Interface> is not applicable for the arguments (Class<Type>)
顺便说一句。我已经通过将 Type.class 向下转换为 Class 来解决它,这样编译器就无法看到 Class 的泛型类型是“Type”而不是“? extends Interface”。
【问题讨论】: