我有一些使用 Boolean.parseBoolean 转换的字符串值。然后我意识到,进行验证时,如果输入为真(不区分大小写),它将返回 true。所有其他值都将返回 false,包括 null 或任何其他字符串,示例:hello。然后我做了如下逻辑:
String input = entityDto().constantValues.get("input");
String message = ("Boolean entity contains invalid data: " + input);
if (input != null) {
if (input.equalsIgnoreCase("true") || input.equalsIgnoreCase("false")) {
return Boolean.parseBoolean(input);
}
}
throw new IllegalStateException(message);
看起来不错,但是我想知道是否有更好的方法来处理真正的布尔检查? 我需要验证输入是真还是假(不区分大小写)。否则抛出 IllegalStateException。 Like类型:boolean代表两个值:true和false。请注意,“true”、“”、0 或 null 等真值和假值不被视为布尔值。
提前致谢
这个主意很好。你可以让它稍微更简洁,理论上更快(尽管我 - 真的 - 怀疑它在这里会很重要):
String input = entityDto().constantValues.get("input");
return switch (input) {
case "true" -> true;
case "false" -> false;
case null, default -> throw new IllegalStateException(
"Boolean entity contains invalid data: " + input);
};
请注意,您可能想也可能不想考虑
switch (input.toLowerCase())
,如果您希望更多字符串有效,可以使用逗号,例如case "true", "on", "1" -> true;
。
switch 语句(java 已有 30 年的功能)被定义为在您尝试打开
null
时抛出 NPE,这就是为什么较新形式的 switch(例如此处使用的 switch 表达式)也会这样做。但是,您可以 case null
更改此行为。这就是为什么你必须在这里写 case null, default
- 你想要 both null
以及任何不是 "true"
或 "false"
的字符串值都以 throw
语句结束。
注意:这将需要 java17,甚至可能需要 java21。