空安全方法调用 Java7

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18152765/
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-08-11 22:50:17  来源:igfitidea点击:

Null-safe Method invocation Java7

javajava-7

提问by Subodh Joshi

I want to get details about this feature of Java7 like this code

我想像这段代码一样获取有关 Java7 的此功能的详细信息

public String getPostcode(Person person)
{
    if (person != null)
    {
        Address address = person.getAddress();
        if (address != null)
        {
            return address.getPostcode();
        }
    }
    return null;
}

Can be do something like this

可以做这样的事情

public String getPostcode(Person person)
{
    return person?.getAddress()?.getPostcode();
}

But frankly its not much clear to me.Please explain?

但坦率地说,我不太清楚。请解释一下?

采纳答案by Rohit Jain

Null-safe method invocation was proposed for Java 7 as a part of Project Coin, but it didn't make it to final release.

作为 Project Coin 的一部分,为 Java 7 提出了空安全方法调用,但它没有最终发布。

See all the proposed features, and what all finally got selected here - https://wikis.oracle.com/display/ProjectCoin/2009ProposalsTOC

查看所有提议的功能,以及最终在此处选择的所有功能 - https://wikis.oracle.com/display/ProjectCoin/2009ProposalsTOC



As far as simplifying that method is concerned, you can do a little bit change:

就简化该方法而言,您可以做一些更改:

public String getPostcode(Person person) {

    if (person == null) return null;
    Address address = person.getAddress();
    return address != null ? address.getPostcode() : null;
}

I don't think you can get any concise and clearer than this. IMHO, trying to merge that code into a single line, will only make the code less clear and less readable.

我认为没有比这更简洁明了的了。恕我直言,试图将该代码合并为一行,只会使代码变得不那么清晰和可读性较差。

回答by Kon

If I understand your question correctly and you want to make the code shorter, you could take advantage of short-circuit operators by writing:

如果我正确理解您的问题并且您想缩短代码,您可以通过编写以下内容来利用短路运算符:

if (person != null && person.getAddress() != null)
    return person.getAddress().getPostCode();

The second condition won't be checked if the first is false because the && operator short-circuits the logic when it encounters the first false.

如果第一个条件为假,则不会检查第二个条件,因为 && 运算符在遇到第一个时会短路逻辑false

回答by Eldar Agalarov

It should work for you:

它应该适合你:

public String getPostcode(Person person) {
    return person != null && person.getAddress() != null ? person.getAddress().getPostcode() : null;
}

Also check this thread: Avoiding != null statements

还要检查这个线程:Avoiding != null statements

回答by radiantRazor

If you want to avoid calling getAddress twice, you can do this:

如果你想避免调用 getAddress 两次,你可以这样做:

Address address;
if (person != null && (address = person.getAddress()) != null){
      return address.getPostCode();
}