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代码   收藏代码
  1. String value = System.getProperty(key);  
  2. boolean b = Boolean.valueOf(value);  
  3. //TODO  

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

Java代码   收藏代码
  1. public static boolean getBoolean(String name) {  
  2.        boolean result = false;  
  3.        try {  
  4.            result = toBoolean(System.getProperty(name));  
  5.        } catch (IllegalArgumentException e) {  
  6.        } catch (NullPointerException e) {  
  7.        }  
  8.        return result;  
  9.    }  

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

Java代码   收藏代码
  1. System.getPropertyAsBoolean(name)  

是不是见名知义了呢?

 

 

6、瞎想:作者van Hoff本是好意,没想到弄巧成拙,误导不少初次使用此方法的人,查看了下写System类和Boolean类的作者分别为:unascribed和van Hoff,他们正喝着咖啡,一边聊着天,一边写着代码,聊着聊着······(由大家补充吧),结果。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值