问题描述
在代码中我们有很多链式方法,例如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?
我认为最好的是:
obj.getA().getB().getC().getD().isNull()
- 为此,我需要更改我所有的 getter,例如实现一些接口其中包含isNull()
方法.NullObjectHelper.isNull(obj.getA().getB().getC().getD());
- 这将是最好的(我认为是)但是如何实现呢?
obj.getA().getB().getC().getD().isNull()
- for this purpose I will need to change all of my getters, for example implement some interface which containsisNull()
method.NullObjectHelper.isNull(obj.getA().getB().getC().getD());
- this will be the best (I think so) but how to implement this?
推荐答案
从 Java 8 开始,您可以使用像 Optional.isPresent 和 Optional.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);
没有任何方法可能比嵌套的 if-not-null 检查具有更高的运行时效率.
No approach is likely to have greater runtime efficiency than nested if-not-null checks.
这篇关于检查方法链中的最后一个 getter 是否不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!