Java 8's orElse not working as expected

筅森魡賤 提交于 2019-12-28 06:41:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!