如何处理多个空值?

时间:2016-01-14 18:50:14

标签: java if-statement

我们说我有一个SOA。现在我进行服务调用,我得到一个对象,它将嵌套对象作为字段。让我们说:

class A {
 B b;
}
class B {
  C c;
}
class C {
  D d;
}

现在,如果我需要访问来自D类的字段,当我将对象作为来自服务调用的响应时,我需要执行:

if(a == null || a.getB() == null || a.getB().getC() == null || a.getB().getC().getD() == null) {
  throw someexception();
}

是否有一种优雅的方式来处理相同的谓词?

3 个答案:

答案 0 :(得分:10)

您可以使用Optional

D d = Optional.ofNullable(a)
        .map(A::getB)
        .map(B::getC)
        .map(C::getD)
        .orElseThrow(MyNullException::new);

如果您想使用默认值,也可以orElseGet(D::new)

答案 1 :(得分:1)

特定的示例中,您将抛出异常。在这种情况下,这显然是一种特殊情况,因此我们可以使用例外来管理它:

D d;
try {
    d = a.getB().getC().getD();
}
catch (NullPointerException npe) {
    throw new SomeException(npe);
}
doYourStuffWith(d);

如果你没有抛出异常,你就不会这样做;你不想在正常的程序流程中使用异常。在这种情况下,您当前的检查没问题,或者您可以使用一系列if/else或Java 8上下文do that lovely thing Peter showed us中的更具体的异常。 : - )

答案 2 :(得分:0)

你尝试过这样的事吗?

try {

    //Try and do something

} catch(NullPointerException e) {
    //Something was null, therefore an exception was thrown
}
相关问题