为什么以下Java代码会抛出NullPointerException?
public static void main(String[] args) {
getInteger(null);
}
public static Integer getInteger(Number n) {
return (n == null || n instanceof Integer) ? (Integer)n : n.intValue();
}
编辑:我添加了括号,以消除关于“我是否有时返回布尔值”的困惑。
n instanceof Integer
也会失败,因此您基本上要检查两次。 - SomeJavaGuyn.intValue()
改为Integer.valueOf(n.intValue())
(目前所有答案都不正确)。 - assyliasn.intValue()
,它会返回一个原始的整数类型(primitive int),编译器也会对第一部分进行拆箱操作。因此,在编译后的代码中,(Integer) n
就变成了((Integer) n).intValue()
。如果输入为 null,则会抛出 NPE 异常。希望这样解释清楚了。 - Codebender