Null-safe方法调用Java7 [英] Null-safe Method invocation Java7

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

问题描述

我想获得有关此代码的Java7功能的详细信息

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

可以做这样的事情

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

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

解决方案

作为Project Coin的一部分,Java 7提出了空安全方法调用,但它没有进入最终版本。 / p>

查看所有建议的功能,以及最终在这里选择的内容 - https://wikis.oracle.com/display/ProjectCoin/2009ProposalsTOC






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

  public String getPostcode(Person person){ 

if(person == null)返回null;
地址address = person.getAddress();
返回地址!= null? address.getPostcode():null;
}

我认为你不能比这更简洁明了。恕我直言,试图将该代码合并为一行,只会使代码不那么清晰,可读性也会降低。


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

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?

解决方案

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

See all the proposed features, and what all finally got selected here - 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.

这篇关于Null-safe方法调用Java7的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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