三目运算符的坑
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);