如何将字符串对象转换为布尔对象?


当前回答

您可以直接设置布尔值等价于任何字符串的系统类 并访问它的任何地方..

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中。


更新:

也可以使用自动装箱,但它有性能成本。 我建议只在你不得不打石膏的时候使用它,而不是在可以避免打石膏的时候。