Java:unary if - npe [英] Java: unary if - npe

查看:200
本文介绍了Java:unary if - npe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这段代码会导致NPE? Findbugs给我提示,这可能会发生,有时会发生: - )

Why does this code can cause a NPE? Findbugs give me the hint, that this can occur and it does sometimes :-)

任何想法?

public Integer whyAnNPE() {
    return 1 == 2 ? 1 : 1 == 2 ? 1 : null;
}


推荐答案

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

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;
}

重点是我们有两个条件这里的表达。由于 Integer 类型docs / books / jls / third_edition / html / expressions.html#15.25rel =nofollow> 15.25部分

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

涉及可能装箱 int 整数,但条件如下:

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

condition ? Integer : int

涉及可能拆箱整数 int

原始答案

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

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;
    }
}

这实际上是:

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

显然,这里的拆箱步骤将会爆炸。基本上是因为将空表达式隐式转换为 Integer ,并且从 Integer int 通过拆箱。

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.

这篇关于Java:unary if - npe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆