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

标签 java types jvm overloading

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/

相关文章:

java - 比较 enum java 中的值

types - 显示函数的类型

java - JVM跳转指令的偏移量怎么会是32768呢?

java - 如何使用 VisualVM 分析 Java 应用程序?

Java 程序因某些测试用例超时而失败

java - Springframework 中的单独序列化器

java - 如何使用 Spring 组件注册 POJO 工厂 *方法*?

scala - scala 中的参数接受多种类型

types - 如何设置单元格数据类型

java - JVMJ9GC020E -Xms 对于堆来说太大