问题
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?
回答1:
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.
回答2:
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
.
回答3:
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
回答4:
If you want to avoid calling getAddress twice, you can do this:
Address address;
if (person != null && (address = person.getAddress()) != null){
return address.getPostCode();
}
来源:https://stackoverflow.com/questions/18152765/null-safe-method-invocation-java7