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


当前回答

要获得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 b = Boolean.valueOf(string);

如果字符串不是空值并且等于true(忽略大小写),则b的值为true。

boolean status=false;
if (variable.equalsIgnoreCase("true")) {
   status=true;  
   }

仅当字符串为'true'(不区分大小写)时才支持。稍后您可以使用状态变量。

尝试(取决于你想要的结果类型):

Boolean boolean1 = Boolean.valueOf("true");
boolean boolean2 = Boolean.parseBoolean("true");

优势:

Boolean:它不会创建新的Boolean实例,因此性能更好(并且垃圾收集更少)。它重用任意一个布尔值的两个实例。TRUE或布尔值。false。 布尔型:不需要实例,使用基本类型。

官方文档在Javadoc中。


更新:

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

要获得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

在2018年1月,最好的方法是使用apache的BooleanUtils.toBoolean。

这将把任何布尔值如字符串转换为布尔值,例如Y, yes, true, N, no, false等。

非常方便!