Boolean.getBoolean()那些坑

今天使用自定义注解时,用到了Boolean.getBoolean(),原以为Boolean.getBoolean("true"),会返回true,结果是false。
  细看源码发现:

/**
 * Returns {@code true} if and only if the system property
 * named by the argument exists and is equal to the string
 * {@code "true"}. (Beginning with version 1.0.2 of the
 * Java<small><sup>TM</sup></small> platform, the test of
 * this string is case insensitive.) A system property is accessible
 * through {@code getProperty}, a method defined by the
 * {@code System} class.
 * <p>
 * If there is no property with the specified name, or if the specified
 * name is empty or null, then {@code false} is returned.
 *
 * @param   name   the system property name.
 * @return  the {@code boolean} value of the system property.
 * @throws  SecurityException for the same reasons as
 *          {@link System#getProperty(String) System.getProperty}
 * @see     java.lang.System#getProperty(java.lang.String)
 * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
 */
public static boolean getBoolean(String name) {
    boolean result = false;
    try {
        result = parseBoolean(System.getProperty(name));
    } catch (IllegalArgumentException | NullPointerException e) {
    }
    return result;
}

看注释第一行就知道了,仅当入参为系统属性且为“true”时才会返回true。
Boolean的正确用法:

public void testGet() {
        System.out.println(Boolean.getBoolean("true")); // false
        //
        System.out.println(Boolean.parseBoolean("true")); // true
        System.out.println(Boolean.parseBoolean("True")); // true
        System.out.println(Boolean.valueOf("true")); // true
        System.out.println(Boolean.valueOf("True")); // true
        // getBoolean仅当参数为系统属性且为true时返回true
        String systemProperty = "true";
        System.setProperty("key", systemProperty); // key-value
        System.out.println(Boolean.getBoolean("key"));
    }

欢迎个人转载,但须在文章页面明显位置给出原文连接;
未经作者同意必须保留此段声明、不得随意修改原文、不得用于商业用途,否则保留追究法律责任的权利。

【 CSDN 】:csdn.zxiaofan.com
【GitHub】:github.zxiaofan.com

如有任何问题,欢迎留言。祝君好运!
Life is all about choices! 
将来的你一定会感激现在拼命的自己!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值