可以通过Boolean.valueof来实现字符串到boolean值的转换:
只有字符串为true 且忽略大小写比如:True/TRue/TRUE等返回布尔值true,其他都返回false。
Boolean b1 = Boolean.valueOf("true");
System.out.println(b1);// true
Boolean hh = Boolean.valueOf("hh");
System.out.println(hh);// false
Boolean aFalse = Boolean.valueOf("false");
System.out.println(aFalse);//false
Boolean aTrue = Boolean.valueOf("True");
System.out.println(aTrue);//true
Boolean aBoolean = Boolean.valueOf(null);
System.out.println(aBoolean);// false
我们可以看一下源码:
发现它其实是判断是否可以转换为Boolean类型,是的话,就返回true,否则返回false。
/**
* Returns a {@code Boolean} with a value represented by the
* specified string. The {@code Boolean} returned represents a
* true value if the string argument is not {@code null}
* and is equal, ignoring case, to the string {@code "true"}.
*
* @param s a string.
* @return the {@code Boolean} value represented by the string.
*/
public static Boolean valueOf(String s) {
return parseBoolean(s) ? TRUE : FALSE;
}
接着,我们查看parseBoolean()的源码。
我们发现只要传入的字符串不为null且忽略大小写与字符串值true相等就就返回布尔值true,
否则返回false。
/**
* Parses the string argument as a boolean. The {@code boolean}
* returned represents the value {@code true} if the string argument
* is not {@code null} and is equal, ignoring case, to the string
* {@code "true"}. <p>
* Example: {@code Boolean.parseBoolean("True")} returns {@code true}.<br>
* Example: {@code Boolean.parseBoolean("yes")} returns {@code false}.
*
* @param s the {@code String} containing the boolean
* representation to be parsed
* @return the boolean represented by the string argument
* @since 1.5
*/
public static boolean parseBoolean(String s) {
return ((s != null) && s.equalsIgnoreCase("true"));
}