gpt4 book ai didi

java - 在函数重载的情况下,JVM 如何找到要调用的方法(具有最接近匹配的参数)

转载 作者:搜寻专家 更新时间:2023-10-30 21:00:41 24 4
gpt4 key购买 nike

JVM 决定在编译时调用哪个重载方法。我有一个例子:

public class MainClass{

public static void go(Long n) {System.out.println("takes Long ");}
public static void go(Short n) {System.out.println("takes Short ");}
public static void go(int n) {System.out.println("takes int ");}

public static void main(String [] args) {
short y = 6;
long z = 7;
go(y);
go(z);
go((Short)y);
}
}

按照我的理解,应该会打印出如下内容:

takes Short
takes Long
takes Short

...但实际输出是:

takes int
takes Long
takes Short

但是如果我有以下三个函数:

public static void go(Integer n) {System.out.println("takes Integer");}
public static void go(Long n) {System.out.println("takes Long ");}
public static void go(Short n) {System.out.println("takes Short ");}

...并使用以下方式调用它:

int a= 10; and go(i);  //output : takes Integer.

... 为什么 shortint 有区别?

最佳答案

参见 JLS Section 15.12.2 ,对于编译器遵循的规则来确定调用哪个方法。编译器总是选择最具体的方法以防你的方法被重载:

There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is one used at run time to perform the method dispatch.

编译器首先尝试在不装箱或拆箱的情况下解析该方法,如此处引用的那样:

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.

强调我的。

因此,在您的第一个st 代码中,因为short 可以用作int 类型参数的参数。编译器不会使用带有参数 Short 的方法,因为它需要装箱。而在 long 类型的情况下,由于它不能用作类型 int 的参数,因此它会将其装箱为 Long。请记住,加宽优于装箱

在您的第 2 个nd 中,除了将 int 装箱到 Integer 之外别无他法。因此,它调用带有 Integer 参数的方法。

关于java - 在函数重载的情况下,JVM 如何找到要调用的方法(具有最接近匹配的参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17999480/

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