开发过程中遇到一个问题,顺手记录一下。场景如下:
public class PriceVO {
private Double originalPrice;
private Double preferentialPrice;
public Double getOriginalPrice() {return originalPrice;}
public void setOriginalPrice(Double originalPrice) {this.originalPrice = originalPrice;}
public Double getPreferentialPrice() {return preferentialPrice;}
public void setPreferentialPrice(Double preferentialPrice) {this.preferentialPrice = preferentialPrice;}
}
以上是一个实体中有两个均为Double类型的属性,在往属性中set值的时候遇到一个空指针,代码1如下:
public static void main(String[] args) {
PriceVO priceVO = new PriceVO();
//此处省略一系列对price的操作,最终结果有price为null的情况
Double price = null;
//这行报空指针
priceVO.setPreferentialPrice(price != null && price < 0 ? 0 : price);
}
但是如果把代码成以下内容便不会有空指针,代码2改为:
PriceVO priceVO = new PriceVO();
Double price = null;
Double i = 0.0;
//将三目运算符中的所有表达式都改成对象类型,没有基础数据类型参与运算,便不会有空指针
priceVO.setPreferentialPrice(price != null && price < i ? i : price);
System.out.println(JSON.toJSON(priceVO));
还好最终找到了问题所在,在伙伴的帮助下查阅资料得出以下结论:
当第二位和第三位表达式都是包装类型的时候,该表达式的结果才是该包装类型,否则,只要有一个表达式的类型是基本数据类型,则表达式得到的结果都是基本数据类型。如果结果不符合预期,那么编译器就会进行自动拆箱。
由于代码1使用了三目运算符,并且第二、第三位操作数分别是基本类型和对象。就需要对对象进行拆箱操作,由于该price对象为 null,所以在拆箱过程中调用 null.booleanValue() 的时候就报了 NPE。