Nau*_*fal 8 java null nullpointerexception null-coalescing-operator
使用Java,为了安全地访问深层嵌套引用
a.b.c.d.e,我们通常必须在每个级别指定空检查或包装Optional并使用orElse().(与Kotlin/C#等语言a?.b?.c?.d?.e或类似作品不同.
我想知道以下帮助方法是否是一个合理的替代方法:
public <T> T valueOrNull(Supplier<T> expression) {
try {
return expression.get();
} catch (NullPointerException e) {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
然后可以安全地使用它value = valueOrNull(() -> a.b.c.d.e).
注意:据我所知,NullPointerException由于性能原因等原因,捕获s通常是不受欢迎的,但是想知道这里的用法是否是一个合理的例外.
小智 2
您可以编写一个接受值和 getter 来转换它的函数,如下所示
public static <T1, T2> T1 coalesce(T2 value, Function<T2,T1> f1){
return f1.apply(value);
}
Run Code Online (Sandbox Code Playgroud)
然后你会这样称呼它coalesce(value, Clazz::getA)。
对于链中的每一步,您都需要在合并函数中添加一个附加函数,如下所示
public static <T1, T2, T3> T1 coalesce(T3 value, Function<T3,T2> f1, Function<T2,T1> f2){
T2 t2 = f1.apply(value);
if(t2 == null)
return null;
return f2.apply(t2);
}
Run Code Online (Sandbox Code Playgroud)
深度为二,并且
public static <T1, T2, T3, T4> T1 coalesce(T4 value, Function<T4,T3> f1, Function<T3,T2> f2, Function<T2,T1> f3){
T3 t3 = f1.apply(value);
if(t3 == null)
return null;
T2 t2 = f2.apply(t3);
if(t2 == null)
return null;
return f3.apply(t2);
}
Run Code Online (Sandbox Code Playgroud)
深度为三,依此类推,更深的深度。
示例代码:
A test1 = new A(null);
A test2 = new A(new B(null));
A test3 = new A(new B(new C(null)));
A test4 = new A(new B(new C("1234")));
System.out.println(coalesce(test1, A::getB, B::getC, C::getS));
System.out.println(coalesce(test2, A::getB, B::getC, C::getS));
System.out.println(coalesce(test3, A::getB, B::getC, C::getS));
System.out.println(coalesce(test4, A::getB, B::getC, C::getS));
System.out.println(coalesce(test2, A::getB));
System.out.println(coalesce(test3, A::getB, B::getC));
Run Code Online (Sandbox Code Playgroud)
A 是具有 B 类成员的类,B 是具有 C 类成员的类,C 是具有 String 类成员的类,并具有适当的 getter。输出如预期:
null
null
null
1234
B@776ec8df
C@41629346
Run Code Online (Sandbox Code Playgroud)
前三种情况为空,其中 C 中的字符串为空,第四种具有字符串的值,第五种和第六种分别返回 B 和 C 类型的对象。
不幸的是,我没有找到一种方法可以使代码变得更短。
| 归档时间: |
|
| 查看次数: |
1682 次 |
| 最近记录: |