Eclipse 与 Javac:泛型的不同编译行为
可能的重复:
泛型在 Eclipse 中编译并运行,但没有t 在 javac 中编译
编译器对于泛型的 null 参数的行为有所不同方法
public static void main(String[] args) {
Class<Object> type1 = String.class;
Class<? extends Object> type2 = String.class;
Class<Object> type3 = get(String.class);
Class<Object> type4 = Foo.<Object, String> get(String.class);
}
public static <I, C extends I> Class<I> get(Class<C> type) {
return null;
}
第一行会产生如下编译错误:
类型不匹配:无法从
Class
转换为Class
这很正常。第二行可以正常工作。
在 eclipse 和 javac 中编译时,第三行的工作方式不同。 Eclipse 会愉快地编译。 Javac 会给我以下错误:
[ERROR] Foo.java:[36,26] incompatible types
[ERROR] found : java.lang.Class<java.lang.String>
[ERROR] required: java.lang.Class<java.lang.Object>
第四行在两个编译器中都能正确编译。
谁能解释发生了什么?谢谢 :)
Possible Duplicate:
Generics compiles and runs in Eclipse, but doesn't compile in javac
Compilers behave differently with a null parameter of a generic method
public static void main(String[] args) {
Class<Object> type1 = String.class;
Class<? extends Object> type2 = String.class;
Class<Object> type3 = get(String.class);
Class<Object> type4 = Foo.<Object, String> get(String.class);
}
public static <I, C extends I> Class<I> get(Class<C> type) {
return null;
}
The first line will generate the following compilation error:
Type mismatch: cannot convert from
Class<String>
toClass<Object>
which is pretty much normal. The second line will work fine.
The third line works differently when compiling in eclipse and in javac. Eclipse will compile happily. Javac will give me the following error:
[ERROR] Foo.java:[36,26] incompatible types
[ERROR] found : java.lang.Class<java.lang.String>
[ERROR] required: java.lang.Class<java.lang.Object>
The forth line compiles correctly in both compilers.
Can anyone explain what is happening? Thank you :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论