JVM如何在函数重载的情况下找到要调用的方法(具有最接近匹配的参数) [英] How JVM finds method (parameter with the closest matching) to call in case of function overloading

查看:339
本文介绍了JVM如何在函数重载的情况下找到要调用的方法(具有最接近匹配的参数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The JVM decides which overloaded method to call at compile time. I have one example:

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);
  }
}

根据我的理解,它应该打印以下内容:

According to my understanding, it should print the following:

takes Short
takes Long
takes Short

...但实际输出为:

... but the actual output is:

takes int
takes Long
takes Short

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

However if I have the following three functions:

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 ");}

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

... and call it using:

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

...为什么 int

推荐答案

参见 JLS第15.12.2节,对于规则编译器如下确定调用方法。如果您的方法超载,编译器总是选择最具体的方法:

See JLS Section 15.12.2, for rules compiler follows to determine which method to invoke. Compiler always chooses the most specific method in case your methods are overloaded:


可能有多个这样的方法,在这种情况下最多选择具体的一个。最具体方法的描述符(签名加返回类型)是在运行时用于执行方法分派的方法。

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.

编译器首先尝试在没有装箱或取消装箱的情况下解决方法:

Compiler first tries to resolve the method without boxing or unboxing as quoted there:


第一阶段(§15.12.2.2)执行重载解析而不允许装箱或拆箱转换,或使用变量arity方法调用。如果在此阶段没有找到适用的方法,则处理继续到第二阶段。

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.

强调我的。

所以,在你的1 st 代码中,因为 short 可以用作 INT 。编译器不会使用参数 Short 的方法,因为这需要装箱。在 long 类型的情况下,因为它不能用作 int 类型的参数,所以它将它装箱到 Long 。请记住加宽优先于拳击

So, in your 1st code, since short can be used as argument for parameter of type int. Compiler will not use the method with parameter Short, as that requires boxing. While in case of long type, since it cannot be used as argument for type int, it goes for boxing it to Long. Remember Widening is preferred over Boxing.

在你的2 nd 中,除了拳击<$>之外别无他法。 c $ c> int 到整数。因此,它使用 Integer 参数调用方法。

In your 2nd, there is no other way than boxing int to Integer. So, it calls method with Integer parameter.

这篇关于JVM如何在函数重载的情况下找到要调用的方法(具有最接近匹配的参数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆