【发布时间】:2015-06-12 12:53:48
【问题描述】:
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)
【问题讨论】:
-
如果我说我刚刚使用 jdk1.8.0_40 成功运行了您的代码,会有帮助吗?只需将其粘贴到一个新的 Idea 项目中,然后单击“运行”并导入 junit 注释。根据您看到的错误,第一个显然 -version with Float 在任何 java 版本上都绝对是错误的。
-
@marvin82:在try Java8 中失败了。
-
marvin82,它编译在java8下用Float很好,没有错误gist.github.com/mariuszs/0a82ca08f55499906ea9
-
我的错,我覆盖了语言级别。很抱歉造成混乱。
标签: java generics java-8 java-7 ambiguous