问题描述
我有一个用例,其中有嵌套类和顶级类的对象.我想获得第N级的值.为了避免NPE,我反复使用吸气剂来实现此目的.示例代码(假设有吸气剂存在)
I have a use case, where I have nested classes and an object of the top class. I want to get a value which is at the Nth level. I'm using getters repetitively to achieve this to avoid NPE. Sample code (assuming getters are there)
class A {
String a1;
String getA1() {
return a1;
}
}
class B {
A a;
A getA() {
return a;
}
}
class C {
B b;
B getB() {
return b;
}
}
class D {
C c;
C getC() {
return c;
}
}
如果我有类D
的对象d
,并且想要获取A
的String a1
,我正在做的事情是:
If I have an object d
of class D
, and want to get the String a1
of A
, what I'm doing is following:
String getAValue(D d) {
String aValue = null;
if(d != null && d.getC() != null && d.getC().getB() != null && d.getC().getB().getA() != null) {
aValue = d.getC().getB().getA().getA1();
}
return aValue;
}
这个重复的a看起来非常丑陋.如何通过使用java8 Optional来避免这种情况?
This repetitive a is looking really ugly. How do I avoid it by using java8 Optional?
我无法修改以上类.假设此d对象作为服务调用返回给我.我只接触这些吸气剂.
I can't modify the above classes. Assume this d object is returned to me as a service call. I'm exposed to these getters only.
推荐答案
在一系列map()
调用中将Optional
与一个好的内衬一起使用:
Use Optional
with a series of map()
calls for a nice one-liner:
String getAValue(D d) {
return Optional.ofNullable(d)
.map(D::getC).map(C::getB).map(B::getA).map(A::getA1).orElse(null);
}
如果链中的任何东西null
,包括d
本身,将执行orElse()
.
If anything is null
along the chain, including d
itself, the orElse()
will execute.
这篇关于用Java 8 Optional替换重复的get语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!