java:引用..是不明确的,方法method1和method2在...匹配

gst*_*low 5 java overloading variadic-functions

我面对相同的代码:

    public class Devk{
        public static void tMeth(Integer... i){
          System.out.print("A");
        }
        public static void tMeth(int... i){
          System.out.print("B");
        }
        public static void main(String args[]){
          tMeth(Integer.valueOf("7"));//compile error
          tMeth(new int[2]); //returns B
          tMeth(new Integer[2]); //returns A
        }

  }
Run Code Online (Sandbox Code Playgroud)

在invokation之后我明白了

java: reference to tMeth is ambiguous, both method tMeth(java.lang.Integer...) in GenericsTest.Test1 and method tMeth(int...) in GenericsTest.Test1 match
Run Code Online (Sandbox Code Playgroud)

method Integer.valueOf("7") 返回Integer包装器.我希望A在控制台中看到.

谁可以解释这种行为并为此提供一般规则?

PS

public static void tMeth(Integer i){
    System.out.print("A");
}
public static void tMeth(int i){
    System.out.print("B");
}
public static void main(String args[]){
    tMeth(1); //returns B
    tMeth(new Integer(1)); //returns A
}
Run Code Online (Sandbox Code Playgroud)

Rus*_*ser 7

编译方法调用时,编译器按此顺序搜索匹配方法:

  1. 尝试找到没有自动装箱/拆箱或varargs的方法.
  2. 如果找不到方法,请查看方法是否匹配使用自动装箱/拆箱.
  3. 如果仍然找不到方法,请查看方法是否匹配使用varargs和autoboxing/unboxing.

在您的情况下,您在这里的步骤(3).由于允许拆箱,因此两种方法均适用.

然后编译器尝试找到最具体的那个.如果一种方法的参数类型具有相同或更具体的特征(例如,String比特定的更具体Object,并且int更具体long),则一种方法比另一种方法更具体.

但在int和之间Integer,两者都不具体; 编译器依赖于上面(2)之前的测试(1)来获得正确的方法,例如foo(int)foo(Integer).

因此,有两种适用的方法,两者都不具体,因此存在歧义误差.

JLS参考