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! 
将来的你一定会感激现在拼命的自己!

发布了140 篇原创文章 · 获赞 157 · 访问量 95万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览