java - 当两个方法都出现在同一个类中时,为什么一个 int... 变量包装成 long

标签 java

下面的代码生成输出:In long。如果我将参数从 (int...x) 更改为 (int x),它将打印 It is int。这是为什么?

public class Sub  {

    void probe(int...x){
        System.out.println("It is int");
    }


    void probe(long x){
        System.out.println("In long");
    }

    public static void main(String[] args){
        int b = 4;
        new Sub().probe(b);
    }
}

最佳答案

Java 编译器将首先选择一个方法,而不考虑任何可变元数方法,即使用 int...。只有当它没有找到任何匹配的方法时,它才会考虑具有变量 arity 的方法。此处,long 匹配,因为 int 可以通过扩展原始转换提升为 long

JLS, Section 15.12.2控制编译器如何选择匹配方法:

The remainder of the process is split into three phases, to ensure compatibility with versions of the Java programming language prior to Java SE 5.0. The phases are:

  1. The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.

This guarantees that any calls that were valid in the Java programming language before Java SE 5.0 are not considered ambiguous as the result of the introduction of variable arity methods, implicit boxing and/or unboxing. However, the declaration of a variable arity method (§8.4.1) can change the method chosen for a given method method invocation expression, because a variable arity method is treated as a fixed arity method in the first phase. For example, declaring m(Object...) in a class which already declares m(Object) causes m(Object) to no longer be chosen for some invocation expressions (such as m(null)), as m(Object[]) is more specific.

  1. The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the third phase.

This ensures that a method is never chosen through variable arity method invocation if it is applicable through fixed arity method invocation.

  1. The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing, and unboxing.

这里只执行第1步,因为long匹配。

关于java - 当两个方法都出现在同一个类中时,为什么一个 int... 变量包装成 long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27992782/

相关文章:

java - 错误 : "schemaLocation value *** must have even number of URI' s. “在 Spring 调度程序中的命名空间上

java - 为什么 NetBeans 在这里显示有关空指针取消引用的警告?

java - org.apache.catalina.core.StandardContext 重新加载后 transient 变量为空

java - 在定义到方法中的类上使用 Gson 返回 null

java - 在 Java 中使用 Class<V> 和泛型类型

java - 从 map 中提取时消除类型转换

java - 将 XML 数据追加到 ArrayList

java - 沉默 log4j

java - Hadoop Mapreduce 字数统计

java - 我不知道为什么我的应用程序不停崩溃