Java 8中的方法模棱两可,为什么?
public static void main(String... args){
then(bar()); // Compilation Error
}
public static <E extends Exception> E bar() {
return null;
}
public static void then(Throwable actual) { }
public static void then(CharSequence actual) { }
编译结果(从命令行)javac Ambiguous.java
)
Ambiguous.java:4: error: reference to then is ambiguous
then(bar());
^
both method then(Throwable) in Ambiguous and method then(CharSequence) in Ambiguous match
1 error
为什么这种方法是模棱两可的?此代码在 Java 7 下成功编译!
将方法栏更改为:
public static <E extends Float> E bar() {
return null;
}
这在编译时没有任何问题,但在 IntelliJ Idea 中报告为错误(无法解析方法)。then(java.lang.FLoat)
此代码在 Java 7 下失败 - :javac -source 1.7 Ambiguous.java
Ambiguous.java:4: error: no suitable method found for then(Float)
then(bar());
^
method Ambiguous.then(Throwable) is not applicable
(argument mismatch; Float cannot be converted to Throwable)
method Ambiguous.then(CharSequence) is not applicable
(argument mismatch; Float cannot be converted to CharSequence)
1 error
Java 版本
java version "1.8.0_40"
Java(TM) SE Runtime Environment (build 1.8.0_40-b25)
Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25, mixed mode)