Java:避免检查嵌套类中的null(深空检查) [英] Java: avoid checking for null in nested classes (Deep Null checking)

查看:775
本文介绍了Java:避免检查嵌套类中的null(深空检查)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下我有一个家庭。它包含一个人员列表。每个(类)Person包含一个(类)地址。每个(类)地址包含一个(类)PostalCode。任何中间类都可以为null。



所以,有没有一个简单的方法到PostalCode,而不必在每一步都检查null?即,有没有办法避免以下菊花链代码?我知道没有本机Java解决方案,但希望如果有人知道一个库或东西。 (检查Commons& Guava,没有看到任何内容)

  if(family!= null){
if (family.getPeople()!= null){
if(family.people.get(0)!= null){
if(people.get(0).getAddress()! {
if(people.get(0).getAddress()。getPostalCode()!= null){
//最终使它做成功!
}
}
}
}
}


$ b b

否,不能更改结构。它是从我不能控制的服务。



不,我不能使用Groovy,它是方便的Elvis运算符。



不,我不想等待Java 8:D



我不敢相信第一个开发者曾经生病厌倦了编写这样的代码,但我还没有能找到一个解决方案。



感谢





llappall

解决方案

您的代码的行为与

相同

  if(family!= null& 
family.getPeople()!= null&
family.people.get )!= null&&
family.people.get(0).getAddress()!= null&&
family.people.get(0).getAddress()。getPostalCode )!= null){
//我的代码
}

短路评估 ,这也是安全的,因为不会评估第二个条件如果第一个是假,第三个将不会被评估,如果第二个是假,....和你不会得到NPE,因为如果它。


Imagine I have a class Family. It contains a List of Person. Each (class) Person contains a (class) Address. Each (class) Address contains a (class) PostalCode. Any "intermediate" class can be null.

So, is there a simple way to get to PostalCode without having to check for null in every step? i.e., is there a way to avoid the following daisy chaining code? I know there's not "native" Java solution, but was hoping if anyone knows of a library or something. (checked Commons & Guava and didn't see anything)

if(family != null) {
    if(family.getPeople() != null) {
        if(family.people.get(0) != null) {
            if(people.get(0).getAddress() != null) {
                if(people.get(0).getAddress().getPostalCode() != null) {
                    //FINALLY MADE IT TO DO SOMETHING!!!
                }
            }
        }
    }
}

No, can't change the structure. It's from a service I don't have control over.

No, I can't use Groovy and it's handy "Elvis" operator.

No, I'd prefer not to wait for Java 8 :D

I can't believe I'm the first dev ever to get sick 'n tired of writing code like this, but I haven't been able to find a solution.

Ideas?

Thanks

--
llappall

解决方案

Your code behaves the same as

if(family != null &&
  family.getPeople() != null &&
  family.people.get(0) != null && 
  family.people.get(0).getAddress() != null &&
  family.people.get(0).getAddress().getPostalCode() != null) { 
       //My Code
}

Thanks to short circuiting evaluation, this is also safe, since the second condition will not be evaluated if the first is false, the 3rd won't be evaluated if the 2nd is false,.... and you will not get NPE because if it.

这篇关于Java:避免检查嵌套类中的null(深空检查)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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