简体   繁体   English

在阅读下面的arrayNode时,有没有更好的方法进行深空点检查?

[英]Is there a better way to have deep null point check while reading the below arrayNode?

I'm doing a null pointer check and would like to know if there is any better way in java 8 other than optional feature 我正在做一个空指针检查,想知道在Java 8中是否有除可选功能以外的更好的方法

if (cake != null && cake.frosting != null && cake.frosting.berries != null) {
//Do something
}

I'm looking if there is any in-line null pointer check 我在寻找是否有任何在线空指针检查

The Elvis operator is what you would want, but it's not part of the Java language. Elvis运算符是您想要的,但它不是Java语言的一部分。 In Groovy you would simply do cake?.frosting?.berries . 在Groovy中,您只需做cake?.frosting?.berries As you said, you could use Optional if(Optional.ofNullable(cake).map(c -> c.getFosting()).map(f -> f.getBerries()).isPresent()) but that IMHO is quite horrible and not the intended use for Optional. 如您所说,您可以使用Optional if(Optional.ofNullable(cake).map(c -> c.getFosting()).map(f -> f.getBerries()).isPresent())但是恕我直言可怕,不是Optional的预期用途。 Your if statement, as you wrote it, is simple and easy to read. 如您所写,if语句非常简单易读。

Maybe something like 也许像

try{
    cake.frosting.berries.toString();
}catch(NullPointerException npe){
    return;
}
//do something

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM