Java:一元 if - npe
为什么这段代码会导致NPE? Findbugs 给了我提示,这种情况可能会发生,而且有时确实会发生:-)
有什么想法吗?
public Integer whyAnNPE() {
return 1 == 2 ? 1 : 1 == 2 ? 1 : null;
}
Why does this code can cause a NPE? Findbugs give me the hint, that this can occur and it does sometimes :-)
Any ideas?
public Integer whyAnNPE() {
return 1 == 2 ? 1 : 1 == 2 ? 1 : null;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑:当我写这个答案时,问题中的代码不存在。
这是另一种让它稍微清晰一些的方法:
重要的一点是我们这里有两个条件表达式。由于 第 15.25 节。
此时,我们会遇到这样的情况:
现在对于剩余条件表达式,前面的要点适用,并且二进制数字提升 已执行。这反过来又调用拆箱作为第一步- 失败了。
换句话说,像这样的条件:
可能涉及将
int
装箱为Integer
,但像这样的条件:可能涉及对
Integer
进行拆箱到int
。原始答案
这是一个相当简单的示例,实际上是有效的Java:
这很有效:
显然,这里的拆箱步骤会很顺利。基本上,这是因为通过拆箱将 null 表达式隐式转换为
Integer
,以及从Integer
隐式转换为int
。EDIT: The code in the question wasn't present when I wrote this answer.
Here's another method to make it slightly clearer:
The important point is that we have two conditional expressions here. The inner one is of type
Integer
due to the last bullet point in the determination of the type as specified in section 15.25.At that point, we've got a situation like this:
Now for the remaining conditional expression, the previous bullet point applies, and binary numeric promotion is performed. This in turn invokes unboxing as the first step - which fails.
In other words, a conditional like this:
involves potentially boxing the
int
to anInteger
, but a conditional like this:involves potentially unboxing the
Integer
toint
.Original answer
Here's a rather simpler example which is actually valid Java:
This is effectively:
Obviously the unboxing step here will go bang. Basically it's because of the implicit conversion of a null expression to
Integer
, and fromInteger
toint
via unboxing.