java - 为什么编译器更喜欢 char 的 int 重载而不是 varargs char 重载?

标签 java overloading

代码

public class TestOverload {

    public TestOverload(int i){System.out.println("Int");}
    public TestOverload(char... c){System.out.println("char");}

    public static void main(String[] args) {
        new TestOverload('a');
        new TestOverload(65);
    }
}

输出

Int
Int

这是预期的行为吗?如果是这样,那为什么?我期待:char,Int

注意:我使用的是 Java 8

最佳答案

当编译器确定选择哪个重载方法时,具有可变参数 (...) 的方法的优先级最低。因此TestOverload(int i)选择 TestOverload(char... c)当您调用 TestOverload与单个 char参数'a' , 因为 char可以自动升级为int .

JLS 15.12.2 :

  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.

  2. 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.

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

编辑:

如果您希望强制编译器调用 TestOverload(char... c)构造函数,你可以传递给构造函数调用一个char[] :

new TestOverload (new char[] {'a'});

关于java - 为什么编译器更喜欢 char 的 int 重载而不是 varargs char 重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32471499/

相关文章:

java - Avro Schema Evolution With GenericData.Record - Mapreduce 过程

java - 将数据保存在缓存、位置的技术?

c++ - 在 C++ 中编写自定义 for 循环

java - Mongodb数据库Schema设计技巧

java - 使用 nunit 使用 jni4net 桥接代码运行测试

java - Spring Boot 和 OVal 上的验证问题

java - Vararg 方法覆盖/重载混淆

c++ - 从 const 调用非常量成员版本

java - 在这种情况下,jvm 如何解析对重载方法的调用?

c# - 方法重载解析意外行为