如何将字符串对象转换为布尔对象?
当前回答
您可以直接设置布尔值等价于任何字符串的系统类 并访问它的任何地方..
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
其他回答
我们创建了soyuz-to库来简化这个问题(将X转换为Y),它只是一组类似问题的SO答案。使用库来解决如此简单的问题可能有些奇怪,但它确实有助于解决许多类似的情况。
import io.thedocs.soyuz.to;
Boolean aBoolean = to.Boolean("true");
请检查它-它非常简单,有很多其他有用的功能
要获得String的布尔值,请尝试以下方法:
public boolean toBoolean(String s) {
try {
return Boolean.parseBoolean(s); // Successfully converted String to boolean
} catch(Exception e) {
return null; // There was some error, so return null.
}
}
如果有错误,它将返回null。 例子:
toBoolean("true"); // Returns true
toBoolean("tr.u;e"); // Returns null
使用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
boolean b = string.equalsIgnoreCase("true");
您可以直接设置布尔值等价于任何字符串的系统类 并访问它的任何地方..
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
推荐文章
- 在Jar文件中运行类
- 带参数的可运行?
- 不区分大小写的“in”
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- 如何在PHP中截断字符串最接近于一定数量的字符?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap
- web - inf在Java EE web应用程序中用于什么?
- Java 8: Lambda-Streams,过滤方法与异常