Boolean.getBoolean问题记录

概述

看过源码后,就能清楚明白,很简单的一个问题,本文记录一下。幸好在发布上线之前,自己在本地自测时,发现这个问题并修复。非常简单的代码,简单到自以为是,根本不需要验证,结果啪啪啪打脸。但若上线后,将是不可预知的损失与后果。告诫自己,一定要自测自测自测。

分析

queryTo是一个Map<String, Object>,里面存有一个Boolean类型的数据键key=cacheApi,想要拿到这个键的值(布尔值),根据这个布尔类型的数据判断走哪一个分支的逻辑。不同分支的逻辑差别十万八千里,所以此行代码实际上很重要。

想都没有想,直接写下如下方法:

Boolean.getBoolean(queryTo.get("cacheApi").toString());

代码就这么放着,没提交没上线。

后面在验证流程逻辑时发现不对劲,才知道这一行代码有问题,于是断点调试,截图如下:
在这里插入图片描述
WTF??
从map里直接get("cacheApi")获取到的数据是true,为啥Boolean.getBoolean(queryTo.get("cacheApi").toString())会得到false?

只能看源码
在这里插入图片描述
继续:
在这里插入图片描述
源码如下:

/**
 * Returns true if and only if the system property named by the argument exists and is equal to, ignoring case, the string "true".
 * A system property is accessible through getProperty, a
 * method defined by the System class. If there is no property with the specified name, or if the specified name is empty or null, then false is returned.
 */
public static boolean getBoolean(String name) {
    boolean result = false;
    try {
        result = parseBoolean(System.getProperty(name));
    } catch (IllegalArgumentException | NullPointerException e) {
    }
    return result;
}

public static boolean parseBoolean(String s) {
    return ((s != null) && s.equalsIgnoreCase("true"));
}

根据上述源码及Java Doc,问题的核心在于System.getProperty(name),即System.getProperty("true"),返回null

至于为什么返回null,因为没有这个系统变量(system property),代码未提前设置。怎么设置呢?

System.setProperty(queryTo.get("cacheApi").toString(), "true");

然后才能获取:

Boolean.getBoolean(queryTo.get("cacheApi").toString());

这就有些无厘头。

Google搜索下来,参考Boolean.getBoolean("true") returns false,应该使用Boolean.valueOf("true")这个API。

结论

解决方案很简单:

MapUtils.getBoolean(queryTo, "cacheApi");

切莫自以为是,须善用工具类。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

johnny233

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值