Java-JDK7编译错误:歧义参考
作者:互联网
我正在尝试将遗留代码库从java1.6迁移到1.7,并且在编译时遇到以下错误:
reference to create is ambiguous, both method create(long,Object…)
in Meta and method create(Object…) in Meta match
这里的Meta是类名.仅当使用JDK1.7进行编译时,才会看到此错误.在1.6中,它运行良好,并且所有依赖项也正常运行.
这两个多态函数如下:
create(long id, Object... paramters) {
....
}
create(Object... paramters) {
....
}
如何解决此问题,以便代码可同时用于1.6编译和1.7编译.
编辑:添加引发错误的呼叫示例:
Id.create(1234);
Id.create(id); // id is a long value
解决方法:
这是由Java 7编译器中的一个修复引起的:
Incompatibilities between JDK 7 and JDK 6
Area: Tools
Synopsis: Changes in Most Specific Varargs Method Selection
Description: The overload resolution algorithm in the javac compiler has been fixed in how it selects the most specific varargs method when more than one method is applicable to a given call-site (see the JLS, Java SE 7 Edition, section 15.12.2.5).
…
While the javac compiler accepts more code than it did prior to JDK 7, this fix also results in a slight source incompatibility in the following case:
class Test {
void foo(int... i) {}
void foo(Object... o) {}
void test() {
foo(1,2,3);
}
}
This code compiles in JDK 6 (the most specific method is foo(int…)). This code does not compile under JDK 7.
为了使代码在两个JDK中都可以工作,您需要给编译器附加提示以选择适当的方法,例如
Id.create(1234, new Object[0]);
Id.create(id, new Object[0]);
这将为JDK6和JDK7调用create(long id,Object …参数),并将为varargs部分传递一个大小为0的数组,在Java 6中使用原始代码的情况下也会传递该数组.
尽管如此,这看起来有点怪异,我可能会选择(为了更好的可读性)重命名其中一种方法,以使方法调用不依赖于签名.
您还应该考虑到Java6处于生命周期的尽头,因此可能的另一种选择是修改代码,使其首先可以与Java7一起编译.
标签:java-7,java 来源: https://codeday.me/bug/20191031/1972681.html