Java 8's orElse not working as expected

后端 未结 1 1758
星月不相逢
星月不相逢 2020-12-06 10:40

Consider the following method which returns a field if it exists or recursively calls itself until the field is found:

private Field getField(Class          


        
相关标签:
1条回答
  • 2020-12-06 11:07

    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));
    }
    
    0 讨论(0)
提交回复
热议问题