如何将字符串对象转换为布尔对象?
当前回答
您可以直接设置布尔值等价于任何字符串的系统类 并访问它的任何地方..
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 = 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
使用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
要获得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
尝试(取决于你想要的结果类型):
Boolean boolean1 = Boolean.valueOf("true");
boolean boolean2 = Boolean.parseBoolean("true");
优势:
Boolean:它不会创建新的Boolean实例,因此性能更好(并且垃圾收集更少)。它重用任意一个布尔值的两个实例。TRUE或布尔值。false。 布尔型:不需要实例,使用基本类型。
官方文档在Javadoc中。
更新:
也可以使用自动装箱,但它有性能成本。 我建议只在你不得不打石膏的时候使用它,而不是在可以避免打石膏的时候。
推荐文章
- 如何在java中格式化持续时间?(如格式H:MM:SS)
- urlencoder .encode(字符串)已弃用,我应该使用什么代替?
- javax.transaction.Transactional vs . org.springframework.transaction.annotation.Transactional
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何找到Java堆大小和内存使用(Linux)?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 我可以将c#字符串值转换为转义字符串文字吗?
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 在c#中解析字符串为日期时间
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠