Java“?”检查null的运算符 - 它是什么? (不是三元!) [英] Java "?" Operator for checking null - What is it? (Not Ternary!)

查看:662
本文介绍了Java“?”检查null的运算符 - 它是什么? (不是三元!)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一篇关于slashdot故事的文章,并且遇到了这个小小的消息:

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


获取最新版本的Java,其中
通过为无限指针测试提供简写语法
来尝试使空指针检查
更容易。只需
为每个方法添加一个问号
调用自动包含
空指针测试,替换
rat的if-then语句嵌套,例如

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();
    } 

我在互联网上搜索过(好吧) ,我花了至少15分钟谷歌搜索java问号的变化,并没有得到什么。所以,我的问题是:有没有关于此的官方文件?我发现C#有一个类似的运算符(??运算符),但是我想得到我正在使用的语言的文档。或者,这只是我使用的三元运算符从未见过。

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.

谢谢!

编辑:链接到文章: http://infoworld.com/d/developer-world/12-programming-mistakes-avoid- 292

推荐答案

最初的想法来自于groovy。作为Project Coin的一部分,Java 7被提议: https:// wiki .openjdk.java.net / display / Coin / 2009 + Proposals + TOC (Elvis和其他Null-Safe运营商),但尚未被接受。

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.

相关的猫王运营商?:被提议为 x!= null提供 x?:y 的简写? x:y ,当x是复数表达式时特别有用。

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

这篇关于Java“?”检查null的运算符 - 它是什么? (不是三元!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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