java - 将字节参数传递给重载方法

标签 java

我从一些测验中获取了这个代码片段,使用 IDE 执行它并得到结果 long, long 但正确答案是 Byte, Byte,为什么我得到不同的结果?该问题与 JDK 11 有关

public class Client {
    static void doCalc(byte... a) {
        System.out.print("byte...");
    }

    static void doCalc(long a, long b) {
        System.out.print("long, long");
    }

    static void doCalc(Byte s1, Byte s2) {
        System.out.print("Byte, Byte");
    }

    public static void main(String[] args) {
        byte b = 5;
        doCalc(b, b);
    }
}

编辑:

代码取自此处:Oracle Certification Overview and Sample Questions (页数:13,问题:5)

最佳答案

所以,如果你浏览一下 Java 语言 specification为了在编译时确定方法签名,这一点将很清楚:

  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.

  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.

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

因此,从上述步骤可以看出,在您的情况下,在第一阶段,Java编译器将找到一个匹配的方法,该方法执行doCalc(long a,long b)。您的方法 doCalc(Byte s1, Byte s2) 在调用期间需要自动装箱,因此它的优先级会降低。

关于java - 将字节参数传递给重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58269412/

相关文章:

java - Apache PDFBox 旋转 PDImageXObject

Java - 如何将数字格式化为 2 char 字符串?

java - 在 Java 中禁用 App Nap

java - 在用户登录/注销时运行 Java 程序的批处理文件

Java 泛型——推断嵌套类型

java - 必要时设置 Java 类路径

java - Android Studio 中的错误?无法访问子类中的 protected 成员

java - Spring - 任务调度程序的问题

java - 读取 Jetty 请求正文会导致 IndexOutOfBoundsException

java - struts2值栈实现