悠悠楠杉
网站页面
正文:
在Java开发中,处理用户输入的布尔字符串(如"true"、"false")是常见需求,但直接使用Boolean.parseBoolean()可能无法覆盖所有场景。例如,用户可能输入"yes"或"1",此时需要更灵活的验证逻辑。本文将介绍几种验证方法,并分析其优缺点。
Boolean.parseBoolean()的局限性Java内置的Boolean.parseBoolean()仅接受"true"(不区分大小写)为true,其他任何输入均返回false。这种设计虽然简单,但缺乏灵活性:
String input = "YES";
boolean result = Boolean.parseBoolean(input); // 返回false
若需支持更多格式(如"yes"、"on"),需自定义逻辑。
通过正则表达式,可以定义更丰富的布尔字符串规则。以下代码支持true/false、yes/no、1/0:
public static boolean parseFlexibleBoolean(String input) {
if (input == null) return false;
return input.matches("(?i)^(true|yes|on|1)$");
}
说明:
- (?i):忽略大小写。
- ^和$:确保全字符串匹配,避免部分匹配(如"true123")。
频繁调用String.matches()会重复编译正则表达式,影响性能。建议使用Pattern预编译:
private static final Pattern BOOLEAN_PATTERN =
Pattern.compile("^(?i)(true|yes|on|1)$");
public static boolean isBoolean(String input) {
return input != null && BOOLEAN_PATTERN.matcher(input).matches();
}
此方法减少运行时开销,尤其适合高频调用场景。
当输入非法时,可抛出异常或返回默认值。以下示例结合严格校验和默认值:
public static boolean parseWithDefault(String input, boolean defaultValue) {
try {
if (input == null) throw new IllegalArgumentException();
String normalized = input.trim().toLowerCase();
if (normalized.equals("true")) return true;
if (normalized.equals("false")) return false;
throw new IllegalArgumentException();
} catch (Exception e) {
return defaultValue;
}
}
整合上述方法,创建一个可复用的BooleanUtils类:
public class BooleanUtils {
private static final Pattern TRUE_PATTERN =
Pattern.compile("^(?i)(true|yes|on|1)$");
public static boolean parse(String input) {
return input != null && TRUE_PATTERN.matcher(input).matches();
}
public static Boolean parseOrNull(String input) {
if (input == null) return null;
if (TRUE_PATTERN.matcher(input).matches()) return true;
if (input.matches("^(?i)(false|no|off|0)$")) return false;
return null;
}
}