为了账号安全,请及时绑定邮箱和手机立即绑定

为什么Javac会抱怨与类的类型参数无关的泛型?

为什么Javac会抱怨与类的类型参数无关的泛型?

为什么Javac会抱怨与类的类型参数无关的泛型?请按顺序阅读代码中的注释,那里的问题详细信息。为什么会发生这种差异?如果可能,请引用JLS。import java.util.*;/**  * Suppose I have a generic class  * @param <T> with a type argument.  */class Generic<T> {     // Apart from using T normally,     T paramMethod() { return null; }     // the class' interface also contains Generic Java Collections     // which are not using T, but unrelated types.     List<Integer> unrelatedMethod() { return null; }}@SuppressWarnings("unused")public class Test {     // If I use the class properly (with qualified type arguments)     void properUsage() {         Generic<String> g = new Generic<String>();         // everything works fine.         String s = g.paramMethod();         List<Integer> pos = g.unrelatedMethod();         // OK error: incompatible types: List<String> := List<Integer>         List<String> thisShouldErrorCompile = g.unrelatedMethod();     }     // But when I use the raw type, *ALL* the generics support is gone, even the Collections'.     void rawUsage() {         // Using Generic<?> as the type turns fixes the warnings below.         Generic g = new Generic();         // OK error: incompatible types: String := Object         String s = g.paramMethod();         // WTF warning: unchecked conversion: List<Integer> := raw List         List<Integer> pos = g.unrelatedMethod();         // WTF warning: unchecked conversion: List<String> := raw List         List<String> thisShouldErrorCompile = g.unrelatedMethod();     }}边注我最初是在IntelliJ IDEA中找到这个的,但是我猜编译器与javac兼容,因为当我用下面的代码编译上面的代码时,它给出了相同的错误/警告。$ javac -version javac 1.7.0_05$ javac Test.java -Xlint:unchecked...$ javac Test.java -Xlint:unchecked -source 1.5 -target 1.5...
查看完整描述

1 回答

?
炎炎设计

TA贡献1808条经验 获得超4个赞

JLS 4.8原始类型开始

仅允许使用原始类型作为对遗留代码兼容性的让步。强烈建议不要在将泛型引入Java编程语言后在编写的代码中使用原始类型。

未从其超类或超接口继承的原始类型C的构造函数(第8.8节),实例方法(第8.4节,第9.4节)或非静态字段(第8.3节)M的类型为与之对应的原始类型在与C对应的通用声明中删除其类型。

如果仔细阅读,这意味着所有类型都将被删除,而不仅仅是您遗漏的类型。


查看完整回答
反对 回复 2019-09-26
  • 1 回答
  • 0 关注
  • 418 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信