我试图从Optional.ispresent(callmethod) 调用私有(private)方法,但出现编译错误。
基本上这是我要检查的条件,如果满足,则调用私有(private)方法。
final OrderLines orderLines = readFromMockFile();
if (null != searchCriteria.getSearch() && StringUtils.isNotEmpty(searchCriteria.getSearch().getValue())) {
applySearchConfig(searchCriteria.getSearch(), orderLines);
}
为了避免空检查,我使用Optional重写了这段代码
Optional.ofNullable(searchCriteria.getSearch())
.map(x -> StringUtils.isNotEmpty(x.getValue()))
.ifPresent(applySearchConfig(searchCriteria.getSearch()));
但是我收到编译错误Optional 类型中的方法 ifPresent(Consumer) 不适用于参数 (OrderLines)
最佳答案
ifPresent()
接受 Consumer
作为参数。
但是您将要调用的方法传递给它(我认为它不会返回 Consumer
):
.ifPresent(applySearchConfig(searchCriteria.getSearch()));
此外,您在这里使用了 map
而不是 filter
:
.map(x -> StringUtils.isNotEmpty(x.getValue()))
因此,您将检查结果映射为 true
或 false
。
您也不希望出现这种情况,因为这会使值呈现出任何结果(true
或 false
)。
尝试一下:
Optional.ofNullable(searchCriteria.getSearch())
.filter(x -> StringUtils.isNotEmpty(x.getValue()))
.ifPresent(x -> applySearchConfig(x, orderLines));
关于java - 如何使用Optional调用类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48505066/