使用参数null重载方法调用 [英] Overloading method calls with parameter null

查看:105
本文介绍了使用参数null重载方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

NULL参数的方法重载

在下面的代码中输出


字符串

String

如果我使用类型 String 的参数删除方法,然后输出

and if I remove the method with the parameter of type String then the output is


对象

Object

我知道当参数类型不完全匹配时方法的重载是如何起作用但我无法理解 null 可以视为对象和/或 String 参数。

I know how overloading of methods acts when the parameter types don't match exactly but I can not understand how null can be treated as an Object and/or a String parameter.

对此有何解释?

class C {

    static void m1(Object x) {
        System.out.print("Object");
    }
    static void m1(String x) {
        System.out.print("String");
    }

    public static void main(String[] args) {
        m1(null);
    }
}


推荐答案

它始终根据使用最具体的方法Java规范,第15.12.2.5节。

It always uses the most specific method according to the Java specs, section 15.12.2.5.

介绍中有相当具体的说明:

The intro is reasonably specific about it:


如果多个成员方法都可访问并适用于方法调用,则必须选择一个为运行时方法调度提供描述符。 Java编程语言使用选择最具体方法的规则。

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

非正式的直觉是,如果第一种方法处理任何调用,则一种方法比另一种方法更具体可以传递给另一个没有编译时类型错误。

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

一般来说,至少对于代码可读性,它是总是最好尽量做到尽可能明确。您可以将 null 转换为与您要调用的签名匹配的类型。但这绝对是一个值得怀疑的做法。它假定每个人都知道这个规则并使代码更难以阅读。

Generally speaking, and at least for code readability, it's always best to try to be as explicit as possible. You could cast your null into the type that matches the signature you want to call. But that's definitely a questionable practice. It assumes everyone knows this rule and makes the code more difficult to read.

但这是一个很好的学术问题,所以我给你的问题+1。

But it's a good academic question, so I +1 your question.

这篇关于使用参数null重载方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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