有人可以解释一下为什么 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
为 true 并且 getValue()
为 null
,则在尝试时会抛出 NullPointerExcetpion
将 null
取消装箱为 long
。
您在 getX()
中不会遇到此问题,因为在表达式 s != null 中? getValue() : new Long(0)
,getValue()
和 new Long(0)
都是 Long
,所以表达式的类型为Long
,并且不进行拆箱。
关于java - 自动装箱/拆箱 java Long 类型作为返回值时出现意外的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55100449/