Java 8的orElse没有按预期工作 [英] Java 8's orElse not working as expected
本文介绍了Java 8的orElse没有按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下方法,如果字段存在则返回该字段,或者在找到该字段之前递归调用自身:
Consider the following method which returns a field if it exists or recursively calls itself until the field is found:
private Field getField(Class<?> clazz, String p) {
Optional<Field> field = Arrays.stream(clazz.getDeclaredFields())
.filter(f -> p.equals(f.getName()))
.findFirst();
return field.isPresent() ? field.get() : getField(clazz.getSuperclass(), p);
}
虽然这有效,但我认为我可以将其缩短为:
While this works, I thought I could shorten it to:
private Field getField(Class<?> clazz, String p) {
return Arrays.stream(clazz.getDeclaredFields())
.filter(f -> p.equals(f.getName()))
.findFirst()
.orElse(getField(clazz.getSuperclass(), p));
}
但奇怪的是 .orElse
部分似乎总是被调用。
But the strange thing is that the .orElse
part seems to always be called.
我在这里缺少什么?
推荐答案
在调用方法之前,始终会评估方法的参数。你想要 orElseGet
,这只需要一个供应商
,只有在可选$时才会被调用c $ c>不存在:
The arguments for a method are always evaluated before the method is called. You want orElseGet
which takes a Supplier
that will only be invoked if the Optional
is not present:
private Field getField(Class<?> clazz, String p) {
return Arrays.stream(clazz.getDeclaredFields())
.filter(f -> p.equals(f.getName()))
.findFirst()
.orElseGet(() -> getField(clazz.getSuperclass(), p));
}
这篇关于Java 8的orElse没有按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文