如何将字符串对象转换为布尔对象?
当前回答
Boolean b = Boolean.valueOf(string);
如果字符串不是空值并且等于true(忽略大小写),则b的值为true。
其他回答
在使用Boolean.valueOf(string)或Boolean.parseBoolean(string)时必须小心。这样做的原因是,如果String不等于“true”,方法总是返回false(这种情况会被忽略)。
例如:
Boolean.valueOf("YES") -> false
由于这种行为,我建议添加一些机制来确保应该转换为布尔值的字符串遵循指定的格式。
例如:
if (string.equalsIgnoreCase("true") || string.equalsIgnoreCase("false")) {
Boolean.valueOf(string)
// do something
} else {
// throw some exception
}
您可以直接设置布尔值等价于任何字符串的系统类 并访问它的任何地方..
System.setProperty("n","false");
System.setProperty("y","true");
System.setProperty("yes","true");
System.setProperty("no","false");
System.out.println(Boolean.getBoolean("n")); //false
System.out.println(Boolean.getBoolean("y")); //true
System.out.println(Boolean.getBoolean("no")); //false
System.out.println(Boolean.getBoolean("yes")); //true
Boolean b = Boolean.valueOf(string);
如果字符串不是空值并且等于true(忽略大小写),则b的值为true。
使用Apache Commons库中的BooleanUtils类:
String[] values= new String[]{"y","Y","n","N","Yes","YES","yes","no","No","NO","true","false","True","False","TRUE","FALSE",null};
for(String booleanStr : values){
System.out.println("Str ="+ booleanStr +": boolean =" +BooleanUtils.toBoolean(booleanStr));
}
结果:
Str =N: boolean =false
Str =Yes: boolean =true
Str =YES: boolean =true
Str =yes: boolean =true
Str =no: boolean =false
Str =No: boolean =false
Str =NO: boolean =false
Str =true: boolean =true
Str =false: boolean =false
Str =True: boolean =true
Str =False: boolean =false
Str =TRUE: boolean =true
Str =FALSE: boolean =false
Str =null: boolean =false
在2018年1月,最好的方法是使用apache的BooleanUtils.toBoolean。
这将把任何布尔值如字符串转换为布尔值,例如Y, yes, true, N, no, false等。
非常方便!
推荐文章
- Intellij IDEA Java类在保存时不能自动编译
- 何时使用Mockito.verify()?
- 在maven中安装mvn到底做什么
- 不可变与不可修改的集合
- 如何在JSON中使用杰克逊更改字段名
- GSON -日期格式
- 如何从线程捕获异常
- 无法解析主机"<URL here>"没有与主机名关联的地址
- 如何在Java中打印二叉树图?
- String.format()在Java中格式化双重格式
- com.jcraft.jsch.JSchException: UnknownHostKey
- Java中的操作符重载
- 如何加速gwt编译器?
- 如何删除表中特定列的第一个字符?
- 在Hibernate中重新连接分离对象的正确方法是什么?