三目运算符发生空指针异常的坑

三目运算符的坑

public static void main(String[] args) {
	// 报错。三目运算符有个很隐蔽的操作,会把nullValue转换成跟 "-1L" 同样的类型,即原始类型(primitive type)。null值转原始类型自然出现NPE
	Long nullValue = null;
	Long l = true ? nullValue : -1L;

	// 不报错。null不会被转为原始类型
	Long l2 = true ? null : -1L;

	// 不报错:nullValue可以转为跟 "new Long(-1)" 一样的类型,即包装类,而包装类允许null
	Long l3 = true ? nullValue : new Long(-1);
}

解决

使用三目运算符,要考虑到两个选择的类型要一致,即flag ? value1 : value2中的value1和value2的类型要相同,不要出现一个是包装类,一个是原始类型。如:

Long time = flag ? jo.getJSONObject("executeContext").getLong("executeTime") : -1L;

// 要改成
Long time = flag ? jo.getJSONObject("execute   Context").getLong("executeTime") : new Long(-1);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值