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
        }
  }
在invokation之后我明白了
java: reference to tMeth is ambiguous, both method tMeth(java.lang.Integer...) in GenericsTest.Test1 and method tMeth(int...) in GenericsTest.Test1 match
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
}
编译方法调用时,编译器按此顺序搜索匹配方法:
在您的情况下,您在这里的步骤(3).由于允许拆箱,因此两种方法均适用.
然后编译器尝试找到最具体的那个.如果一种方法的参数类型具有相同或更具体的特征(例如,String比特定的更具体Object,并且int更具体long),则一种方法比另一种方法更具体.
但在int和之间Integer,两者都不具体; 编译器依赖于上面(2)之前的测试(1)来获得正确的方法,例如foo(int)和foo(Integer).
因此,有两种适用的方法,两者都不具体,因此存在歧义误差.
| 归档时间: | 
 | 
| 查看次数: | 7745 次 | 
| 最近记录: |