Boolean.getBoolean(String name)方法分析
?
?Boolean.getBoolean(String name)根据方法名可能认为当name为"true"时,返回true,当为其它值或空时为false
?? ?查看Boolean.getBoolean(String name)源码解析如下:
?
?? ? ? ?returns ?true ?if and only if the system property??named by the argument exists and is equal to the string?
?? ?true.?
?? ? ? ?根据源码解析可知,该方法是查询系统参数name,如果name值为true,则返回true,当不存在或是其它值时返回false。
?? ?例如:
?
?? ? ? ? System.setProperty("name", "true");
?? ? ? ? Boolean.getBoolean("name"); ?//返回true
?? ? ? ? Boolean.getBoolean("true"); ??//返回false
?
?
?? ? ? ? 查看源码实现如下:
?? ? ? ?public static boolean getBoolean(String name) {
?? ? ? ?boolean result = false;
?? ? ? ?try {
?? ? ? ? ? ?result = toBoolean(System.getProperty(name));
?? ? ? ?} catch (IllegalArgumentException e) {
?? ? ? ?} catch (NullPointerException e) {
?? ? ? ?}
?? ? ? ?return result;
?? ? ? }
?? ? ? 可知,该方法是查看系统参数。
?? ? ? 如果想坚持字符串是否为true,可用下面的方法:
?? ? ???Boolean.parseBoolean("true") //jdk1.5之后推荐使用。
?? ? ? ?Boolean("true").booleanValue()
?
---------------------------------------------
1、今天遇到这样一件事:想把String类型的true和false转换成boolean的原生类型,于是顺手的用Boolean.<alt+/>(快捷键),jdk提供了一个static 的 getBoolean(name)方法,调用之后并不是我预期的结果。最先值得怀疑的应该是自己代码有问题。细查后原来是被此方法名误解了。
?
2、这个方法名起的很邪恶。就是被他的字面意思给误解了。
?
3、仔细看了看文档
jdk 写道Returns true if and only if the system property named by the argument exists and is equal to the string "true". (Beginning with version 1.0.2 of the JavaTM platform, the test of this string is case insensitive.) A system property is accessible through getProperty, a method defined by the System class.??当且仅当系统属性的名字存在且他的值为“true”是才返回true,不知道大家在第一次有没有被误导的,我反正被他欺骗了。
?
4、提供这样的一个方法究竟有什么用处了。我相信作者van Hoff最初的想法是很好的,在没有这个方法之前,如果想获取系统属性的值转换成Boolean类型操作的话通常就是:
Java代码??
?而现在可以直接用getBoolean方法了,其实他也就是在这方法里封装了一下string——>boolean转换的步骤,请看源代码:
Java代码??
?5、对此方法的一些见解:本应是作为System类中的一个方法,现在把他放在Boolean类中,试想如果是这样写:
Java代码??
是不是见名知义了呢?
?
?
6、瞎想:作者van Hoff本是好意,没想到弄巧成拙,误导不少初次使用此方法的人,查看了下写System类和Boolean类的作者分别为:unascribed和van Hoff,他们正喝着咖啡,一边聊着天,一边写着代码,聊着聊着······(由大家补充吧),结果。。。