java 将 null 传递给首选 String 而不是 Object 的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15046763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:19:16  来源:igfitidea点击:

Passing null to the method preferring String, not Object

javastringoopobject

提问by Suresh Atta

I am facing an issue in my program and I made it clear with a small code snippet below. Can anyone explain why this is happening?

我在我的程序中遇到了一个问题,我用下面的一个小代码片段清楚地说明了这一点。谁能解释为什么会这样?

class ObjectnullTest {

    public void printToOut(String string) {

        System.out.println("I am null string");
    }


    public void printToOut(Object object)

        System.out.println("I am  null object");
    }



class Test {

    public static void main(String args[]) {

        ObjectnullTest a = new ObjectnullTest();
        a.printToOut(null);

    }
}

This always prints I am null string.

这总是打印I am null string.

I want to know the reason so that I can modify the code .

我想知道原因,以便我可以修改代码。

回答by PermGenError

It's because In case of method Overloading

这是因为在方法重载的情况下

The most specific method is choosen at compile time.

在编译时选择最具体的方法。

As 'java.lang.String' is a more specific typethan 'java.lang.Object'. In your case the method which takes 'String' as a parameter is choosen.

因为“java.lang.String”是比“java.lang.Object”更具体的类型。在您的情况下,选择了将“String”作为参数的方法。

Its clearly documented in JLS:

它清楚地记录在JLS 中

The second step searches the type determined in the previous step for member methods. This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable, that is, declarations that can be correctly invoked on the given arguments.

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.

第二步在上一步确定的类型中搜索成员方法。这一步使用方法的名称和参数表达式的类型来定位既可访问又适用的方法,即可以对给定参数正确调用的声明。

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

回答by Patricia Shanahan

I agree with the existing comment about selection of the most specific method. You can force your null to be treated as an Object reference, eliminating use of the String argument method, by casting it:

我同意关于选择最具体方法的现有评论。您可以强制将您的 null 视为对象引用,通过强制转换它来消除使用 String 参数方法:

a.printToOut((Object)null);

回答by lets debug the issue

please see section 15.12.2.5 of jls that give in detail how to choose

请参阅 jls 的第 15.12.2.5 节详细说明如何选择

The most specific method is choosen at compile time

在编译时选择最具体的方法