Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8's orElse not working as expected

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?

like image 384
helpermethod Avatar asked Jul 27 '15 15:07

helpermethod


1 Answers

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));
}
like image 56
Alex - GlassEditor.com Avatar answered Nov 12 '22 04:11

Alex - GlassEditor.com