Eclipse 与 Javac:泛型的不同编译行为

发布于 2024-12-14 02:51:32 字数 1274 浏览 1 评论 0原文

可能的重复:
泛型在 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> to Class<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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文