autocoxing / unboxing java时出现意外的NullPointerException长类型为返回值[duplicate]

问题描述 投票:2回答:1

这个问题在这里已有答案:

有人可以解释为什么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)
java nullpointerexception autoboxing scjp
1个回答
2
投票

表达式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,并且不会发生拆箱。

© www.soinside.com 2019 - 2024. All rights reserved.