问题
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?
回答1:
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));
}
来源:https://stackoverflow.com/questions/31657306/java-8s-orelse-not-working-as-expected