Java:一元 if - npe

发布于 2024-12-10 13:35:05 字数 174 浏览 0 评论 0原文

为什么这段代码会导致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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风流物 2024-12-17 13:35:05

编辑:当我写这个答案时,问题中的代码不存在。

这是另一种让它稍微清晰一些的方法:

public static Integer maybeCrash(boolean crash) {
    return true ? (crash ? null : 1) : 0;
}

重要的一点是我们这里有两个条件表达式。由于 第 15.25 节

此时,我们会遇到这样的情况:

public static Integer maybeCrash(boolean crash) {
    Integer tmp = null;
    return true ? tmp : 0;
}

现在对于剩余条件表达式,前面的要点适用,并且二进制数字提升 已执行。这反过来又调用拆箱作为第一步- 失败了。

换句话说,像这样的条件:

condition ? null-type : int

可能涉及将 int 装箱为 Integer,但像这样的条件:

condition ? Integer : int

可能涉及对 Integer 进行拆箱到int


原始答案

这是一个相当简单的示例,实际上是有效的Java:

public class Test {
    public static void main(String[] args) {
        int x = args.length == 0 ? 1 : null;
    }
}

这很有效:

int tmp;
if (args.length == 0) {
   tmp = 1;
} else {
   Integer boxed = null;
   tmp = boxed.intValue();
}

显然,这里的拆箱步骤会很顺利。基本上,这是因为通过拆箱将 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:

public static Integer maybeCrash(boolean crash) {
    return true ? (crash ? null : 1) : 0;
}

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:

public static Integer maybeCrash(boolean crash) {
    Integer tmp = null;
    return true ? tmp : 0;
}

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:

condition ? null-type : int

involves potentially boxing the int to an Integer, but a conditional like this:

condition ? Integer : int

involves potentially unboxing the Integer to int.


Original answer

Here's a rather simpler example which is actually valid Java:

public class Test {
    public static void main(String[] args) {
        int x = args.length == 0 ? 1 : null;
    }
}

This is effectively:

int tmp;
if (args.length == 0) {
   tmp = 1;
} else {
   Integer boxed = null;
   tmp = boxed.intValue();
}

Obviously the unboxing step here will go bang. Basically it's because of the implicit conversion of a null expression to Integer, and from Integer to int via unboxing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文