我想這可能與Why does a generic cast of a List<? extends Set..> to List<Set..> succeed on Sun JDK 6 but fail to compile on Oracle JDK 7?JDK 7中的類型推斷在JDK 6中比JDK 6更具限制性?
如果我們把下面的類,他們編細下JDK 6:
public final class Foo<V> {
private final V value;
private Foo(final V value) {
this.value = value;
}
public static <T, R extends T> Foo<T> of(final R value) {
return new Foo<T>(value);
}
}
final class Tester {
@Test(groups="unit")
public static void test() {
bar(Foo.of(BigDecimal.ZERO)); // This line fails in JDK 7 but not JDK 6
}
private static void bar(final Foo<? extends Number> target) {
assert target != null;
}
}
然而,JDK 7下,我收到以下錯誤:
[ERROR] \work\fsb-core\src\test\java\com\fsb\core\Foo.java:[42,8] error:
method bar in class Tester cannot be applied to given types;
我認爲JDK 7中類型推斷的限制較少(例如,添加構造函數推理)。但是,此處編譯器拒絕在JDK 6下有效的類型。
這是一個錯誤?或者推理規則對方法更嚴格?
Java 8(1.8.0_25)這個編譯就好了。 – Lii 2015-04-04 16:21:40