Check if last getter in method chain is not null

前端 未结 3 720
春和景丽
春和景丽 2020-12-06 12:31

In code we have got a lot of chain methods, for example obj.getA().getB().getC().getD(). I want to create helper class which will check if method getD()

3条回答
  •  佛祖请我去吃肉
    2020-12-06 12:55

    As of Java 8 you can use methods like Optional.isPresent and Optional.orElse to handle null in getter chains:

    boolean dNotNull = Optional.ofNullable(obj)
                  .map(Obj::getA)
                  .map(A::getB)
                  .map(B::getC)
                  .map(C::getD)
                  .isPresent();
    

    While this is preferable to catching NullPointerException the downside of this approach is the object allocations for Optional instances.

    It is possible to write your own static methods that perform similar operations without this overhead:

    boolean dNotNull = Nulls.isNotNull(obj, Obj::getA, A::getB, B::getC, C::getD);
    

    For a sample implementation, see the Nullifier type here.

    No approach is likely to have greater runtime efficiency than nested if-not-null checks.

提交回复
热议问题