java – 使用原始类型和包装类的varargs重载时为什么会出现模糊错误?
|
参见英文答案 >
Ambiguous varargs methods4个
情况1 public class Test {
public void display(int a) {
System.out.println("1");
}
public void display(Integer a) {
System.out.println("2");
}
public static void main(String[] args) {
new Test().display(0);
}
}
输出为:1 案例#2 public class Test {
public void display(int... a) {
System.out.println("1");
}
public void display(Integer... a) {
System.out.println("2");
}
public static void main(String[] args) {
new Test().display(0);
}
}
编译错误: The method display(int[]) is ambiguous for the type Test 解决方法在第一个示例中,display(int)方法在严格调用上下文中调用,而display(Integer)在松散调用上下文中调用(因为需要自动装箱).因此编译器根据JLS选择display(int)方法.调用上下文在这里解释 JLS 5.3. Invocation Contexts在第二个示例中,两个方法都在松散的调用上下文中调用,因此编译器需要找到最具体的方法JLS 15.12.2.5 Choosing the Most Specific Method.由于int不是Integer的子类型,因此没有最具体的方法,编译器会抛出编译错误. 你可以在Method overload ambiguity with Java 8 ternary conditional and unboxed primitives找到类似编译错误的解释 适用于此案例的部分:
对于第一个示例,只有display(int)方法在第一个阶段匹配,因此选择它.对于第二个示例,两个方法在第三阶段匹配,因此选择最具体方法算法发挥作用JLS 15.12.2.5 Choosing the Most Specific Method:
如前所述,由于int< ;: Integer不满足,因此没有最具体的方法. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
