這段代碼編譯在Eclipse中,但不是在javac的:下界通配符引起麻煩的javac,而不是Eclipse的
import java.util.function.Consumer;
public class Test {
public static final void m1(Consumer<?> c) {
m2(c);
}
private static final <T> void m2(Consumer<? super T> c) {
}
}
javac的輸出:
C:\Users\lukas\workspace>javac -version
javac 1.8.0_92
C:\Users\lukas\workspace>javac Test.java
Test.java:5: error: method m2 in class Test cannot be applied to given types;
m2(c);
^
required: Consumer<? super T>
found: Consumer<CAP#1>
reason: cannot infer type-variable(s) T
(argument mismatch; Consumer<CAP#1> cannot be converted to Consumer<? super T>)
where T is a type-variable:
T extends Object declared in method <T>m2(Consumer<? super T>)
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
1 error
----------------------------------------------------------------
哪個編譯器是錯誤的,爲什麼? (Eclipse bug report and parts of discussion here)
即使'javac'版本早9b29編譯這個唯一。 – Holger
非常感謝您深入挖掘這一點。很高興看到使用Java 9,現在兩種編譯器的行爲方式都是一樣的! :) –
我也很欣慰,看到這個融合:) –