检查方法链中的最后一个 getter 是否不为空 [英] Check if last getter in method chain is not null

查看:27
本文介绍了检查方法链中的最后一个 getter 是否不为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在代码中我们有很多链式方法,例如obj.getA().getB().getC().getD().我想创建帮助程序类,它将检查方法 getD() 是否不为空,但在此之前我需要检查所有以前的 getter.我可以这样做:

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() isn't null, but before that I need to check all previous getters. I can do it in this way:

try {
    obj.getA().getB().getC().getD();
}
catch (NullPointerException e) {
    // some getter is null
}

或(这是愚蠢的")

if (obj!null && obj.getA()!=null && obj.getA().getB()!=null && ...) {
    obj.getA().getB().getC().getD();
}
else {
    // some getter is null
}

我不想每次在我的代码中使用 try{} catch() 来检查它.达到此目的的最佳解决方案是什么?

I don't want to check it every time using try{} catch() in my code. What is the best solution for this purpose?

我认为最好的是:

  1. obj.getA().getB().getC().getD().isNull() - 为此,我需要更改我所有的 getter,例如实现一些接口其中包含 isNull() 方法.
  2. NullObjectHelper.isNull(obj.getA().getB().getC().getD()); - 这将是最好的(我认为是)但是如何实现呢?
  1. obj.getA().getB().getC().getD().isNull() - for this purpose I will need to change all of my getters, for example implement some interface which contains isNull() method.
  2. NullObjectHelper.isNull(obj.getA().getB().getC().getD()); - this will be the best (I think so) but how to implement this?

推荐答案

从 Java 8 开始,您可以使用像 Optional.isPresentOptional.orElse 处理 getter 链中的 null:

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

虽然这比捕获 NullPointerException 更可取,但这种方法的缺点是 Optional 实例的对象分配.

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

有关示例实现,请参阅 Nullifier此处输入.

没有任何方法可能比嵌套的 if-not-null 检查具有更高的运行时效率.

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

这篇关于检查方法链中的最后一个 getter 是否不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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