gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:30:03 25 4
gpt4 key购买 nike

我从一些测验中获取了这个代码片段,使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com