问题描述
今天早上我遇到了一个非常奇怪的NPE,并将其简化为一个简单的例子。这是一个JVM错误还是正确的行为?
I ran across a very weird NPE this morning, and reduced it to a simple example. Is this a JVM bug or correct behavior?
public class Test1 {
class Item {
Integer id = null;
public Integer getId() {return id;}
}
public Integer f() {
Item item = new Item();
// this works:
//return item == null ? new Integer(1) : item.getId();
// NPE??
return item == null ? 1 : item.getId();
}
public static void main(String[] args) {
Test1 t = new Test1();
System.out.println("id is: " + String.valueOf(t.f()));
}
}
编译运行输出:
$ javac Test1.java
$ java Test1
Exception in thread "main" java.lang.NullPointerException
at Test1.f(Test1.java:12)
at Test1.main(Test1.java:16)
$
推荐答案
表达式的类型 item == null? 1:item.getId()
是 int
不是整数
。因此,Java需要将 Integer
自动解包到 int
(导致 NullPointerException
)。然后它自动将结果返回到 Integer
(如果不是 NullPointerException $ c,那么它将 $ c>)从方法返回。
The type of the expression item == null ? 1 : item.getId()
is int
not Integer
. Therefore, Java needs to auto-unbox your Integer
to an int
(causing the NullPointerException
). Then it auto-boxes the result back to an Integer
(well it would if not for the NullPointerException
) to return from the method.
另一方面,表达式 item == null? new Integer(1):item.getId()
的类型为 Integer
,不需要自动取消装箱。
On the other hand, the expression item == null ? new Integer(1) : item.getId()
has a type of Integer
and no auto-unboxing needs to be done.
当你自动取消装箱 null
整数
时,你得到一个 NullPointerException
(参见)这就是你所经历的。
When you auto-unbox a null
Integer
, you get a NullPointerException
(see Autoboxing) and that is what you are experiencing.
要回答你的问题,这是正确的行为。
To answer your question, this is correct behavior.
这篇关于具有自动装箱功能的三元运算符中的Java NPE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!