Java 8’s orElse not working as expected

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));
}

Leave a Comment