上周四有人在工作时向我展示了一个编译错误,我无法以干净的方式修复它,从那以后它一直困扰着我.
问题是泛型相关,我重新构建了生成编译错误的简化版本的代码.错误发生在下面显示的最后一行代码中.
我一直在寻找各种各样的互联网,但似乎找不到一个合适的解释为什么Java编译器不接受代码.我想如果它允许代码,那么可能会在Bar.operationOnBar()中创建一个类转换问题,但我不知道如何.
有人可以请教我为什么不编译?
public interface Interface {
}
public class Type implements Interface {
}
public class Bar {
public Bar(Class clazz) {
}
public void operationOnBar(Class arg){
}
}
public class Foo {
public Bar bar(Class clazz){
return new Bar(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) in the type Bar is not applicable for the arguments (Class)
顺便说一句.我通过向下转换Type.class来解决它,这样编译器就无法看到Class的泛型类型是“Type”而不是“?extends Interface”.