java三目运算符 null,Java“?”检查null的运算符 - 它是什么? (不是三元!)

I was reading an article linked from a slashdot story, and came across this little tidbit:

Take the latest version of Java, which

tries to make null-pointer checking

easier by offering shorthand syntax

for the endless pointer testing. Just

adding a question mark to each method

invocation automatically includes a

test for null pointers, replacing a

rat's nest of if-then statements, such

as:public String getPostcode(Person person) {

String ans= null;

if (person != null) {

Name nm= person.getName();

if (nm!= null) {

ans= nm.getPostcode();

}

}

return ans

}

With this:public String getFirstName(Person person) {

return person?.getName()?.getGivenName();

}

I've scoured the internet (okay, I spent at least 15 minutes googling variations on "java question mark") and got nothing. So, my question: is there any official documentation on this? I found that C# has a similar operator (the "??" operator), but I'd like to get the documentation for the language I'm working in. Or, is this just a use of the ternary operator that I've never seen before.

Thanks!

解决方案

The original idea comes from groovy. It was proposed for Java 7 as part of Project Coin: https://wiki.openjdk.java.net/display/Coin/2009+Proposals+TOC (Elvis and Other Null-Safe Operators), but hasn't been accepted yet.

The related Elvis operator ?: was proposed to make x ?: y shorthand for x != null ? x : y, especially useful when x is a complex expression.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值