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));
}
But the strange thing is that the .orElse
part seems to always be called.
What am I missing here?
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With