为什么原始类型将调用第一个而不是包装类?

问题描述:

public class A {

   public void test(Integer i) {
       System.out.println("In Wrapper Method");
   }

   public void test(int i) {
       System.out.println("In primitive Method");
   }

   public static void main(String args[]) {
       A a = new A();
       a.test(5);
   }


}

从main和pass整型参数调用测试方法,然后它将调用接受基本类型的方法作为参数。我只想知道为什么它调用原始类型方法,而不是接受包装类作为参数的方法?是否有任何规则,哪个java跟随调用方法?

When I will call test method from main and pass integer argument, then it will call the method which accept primitive type as argument. I just want to know that why it call primitive type method rather than the method who accepts wrapper class as argument? Is there any rule, which java follow to call methods?

感谢,

作为一个粗略的经验法则,当在不同的重载之间进行选择时,Java使用最接近的匹配方法作为参数表达式的声明类型。在这种情况下,当方法调用时, test(int i) test(Integer i)$ c> test(5),因为后者需要一个类型提升(自动加载)来使实际的参数类型正确。

As a rough "rule of thumb", Java uses the closest matching method for the declared types of the argument expressions when choosing between different overloads. In this case test(int i) is closer than test(Integer i) when the method is called as test(5), because the latter requires a type promotion (auto-boxing) to make the actual argument type correct.

事实上,决策过程比这更复杂,但是经验法则在大多数情况下都有效。

In fact the decision making process is rather more complicated than this, but the "rule of thumb" works in most cases.