您的位置:首页 > 其它

坑爹的 Boolean.getBoolean(String name)

2013-02-25 14:56 148 查看
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代码  



String value = System.getProperty(key);  

boolean b = Boolean.valueOf(value);  

//TODO  

 而现在可以直接用getBoolean方法了,其实他也就是在这方法里封装了一下string——>boolean转换的步骤,请看源代码:

Java代码  



public static boolean getBoolean(String name) {  

       boolean result = false;  

       try {  

           result = toBoolean(System.getProperty(name));  

       } catch (IllegalArgumentException e) {  

       } catch (NullPointerException e) {  

       }  

       return result;  

   }  

 5、对此方法的一些见解:本应是作为System类中的一个方法,现在把他放在Boolean类中,试想如果是这样写:

Java代码  



System.getPropertyAsBoolean(name)  

是不是见名知义了呢?

 

 

6、瞎想:作者van Hoff本是好意,没想到弄巧成拙,误导不少初次使用此方法的人,查看了下写System类和Boolean类的作者分别为:unascribed和van Hoff,他们正喝着咖啡,一边聊着天,一边写着代码,聊着聊着······(由大家补充吧),结果。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐