这个问题在这里已有答案:
有人可以解释为什么getY()方法导致NullPointerException。
public class NullTest {
private String s = "";
public Long getValue() {
return null;
}
public Long getX() {
return s != null ? getValue() : new Long(0);
}
public Long getY() {
return s != null ? getValue() : 0L;
}
public static void main(String[] args) {
NullTest nt = new NullTest();
System.out.println("x = " + nt.getX());
System.out.println("y = " + nt.getY());
}
}
样本输出:
x = null
Exception in thread "main" java.lang.NullPointerException
at NullTest.getY(NullTest.java:13)
at NullTest.main(NullTest.java:19)
表达式s != null ? getValue() : 0L
的类型是long
,而不是Long
。因此,如果s != null
是真的并且getValue()
是null
,那么当试图将NullPointerExcetpion
拆开到null
时,会抛出long
。
你没有在getX()
中得到这个问题,因为在表达式s != null ? getValue() : new Long(0)
中,getValue()
和new Long(0)
都是Long
,因此表达式的类型是Long
,并且不会发生拆箱。