Java 是否有一种更干净的方法可以在不返回“可选”的情况下使用此选项;不适用;在三个地方?
目标是检查Java 是否有一种更干净的方法可以在不返回“可选”的情况下使用此选项;不适用;在三个地方?,java,optional,Java,Optional,目标是检查Throwable消息中的子字符串,如果找到,则返回子字符串,否则返回NA。 context.getRootCauseeException()和Throwable.getMessage()调用都可能返回null一种可能的方法是将flatMap与findFirst一起使用,而不是map作为: public String getSanitisedMessage() { Throwable rootCause = context.getRootCauseExcept
Throwable
消息中的子字符串,如果找到,则返回子字符串,否则返回NA
。
context.getRootCauseeException()
和Throwable.getMessage()
调用都可能返回null
一种可能的方法是将flatMap
与findFirst
一起使用,而不是map
作为:
public String getSanitisedMessage() {
Throwable rootCause = context.getRootCauseException();
if(rootCause != null) {
return Optional.ofNullable(rootCause.getMessage())
.map(message -> Stream.of(
// clean message substrings we want to find
"Connection timed out",
"Connection reset",
"Connection was lost",
"FTP Fails"
).filter(subString -> message
.toLowerCase()
.contains(subString.toLowerCase())
).findFirst().orElse("NA")
).orElse("NA");
} else return "NA";
}
在我看来,您应该在这里抛出一个异常,并正确地处理它(看起来您稍后要检查字符串)。 如果您想坚持这种方式,可以向context.getMessage()中添加一个默认值(假设这是一个实现上下文的自定义类),然后返回其值 否则,您还可以执行以下操作:
return rootCause == null || rootCause.getMessage() == null ? "NA" :
primaryCauses.stream().map(String::toLowerCase).filter(subString -> rootCause.getMessage()
.toLowerCase().contains(subString)).findFirst().orElse("NA");
我希望是这样(并期待着阅读答案),不过对于开头的
if
,您可能会遇到至少两个问题。我至少可以通过放置final String defaultResult=“NA”来减轻压力代码>在顶部,在两个/三个位置使用它。从java9开始,Optional可以生成一个流,因此它可以被平面映射,在我的具体案例中检查这里我不想抛出异常,因为函数实际上是从MVEL表达式调用的,不要问…:o)
return rootCause == null || rootCause.getMessage() == null ? "NA" :
primaryCauses.stream().map(String::toLowerCase).filter(subString -> rootCause.getMessage()
.toLowerCase().contains(subString)).findFirst().orElse("NA");
Throwable rootCause = context.getRootCauseException();
if (rootCause != null) {
return Stream.of("Connection timed out",
"Connection reset",
"Connection was lost",
"FTP Fails")
.filter(s -> s.equalsIgnoreCase(rootCause.getMessage()))
.findFirst()
.orElse("NA");
}
return "NA";
}