【发布时间】:2016-05-23 20:03:33
【问题描述】:
我们已经开始在使用泛型并且在 Java 6 下成功编译的代码上出现编译错误。这里有一个简单的类来重现:
class Test {
static class Foo<T> {
T t;
Foo(T t) { this.t = t; }
T get() { return t; }
}
static class Bar extends Foo<Long> {
Bar(Long t) { super(t); }
}
static class Foobar<N extends Number> extends Bar {
Foobar() { super(5L); }
}
public static void main(String[] args) {
Bar bar = new Bar(0L);
Long b = bar.get(); // This works
Foobar foobar = new Foobar();
Long fb = foobar.get(); // This generates a compile time error
}
}
产生的错误是:
Test.java:26: error: incompatible types: Object cannot be converted to Long
Long fb = foobar.get(); // This generates a compile time error
有人有什么想法吗?
【问题讨论】:
-
对不起,没有提到编译错误发生在 Java 7 和 8,但不是在 6...
-
奇怪的是,虽然我从命令行使用 jdk1.7.0_13 得到这个编译错误,但这段代码在 Eclipse 中编译得很好,使用相同的编译器(仔细检查“安装的 JRE”是否指向相同的路径,合规级别为 1.7,并使用该 jdk)。
-
我得到了完全一样的 - Eclipse 用 1.8 集编译这个没有错误。很奇怪……
标签: java generics compilation compiler-errors