当我使用三元运算符时抛出 NullPointerException

NullPointerException throws when I use ternary operator

我有以下 return 声明:

public Boolean foo(String booleanString){  
    return ("true".equals(booleanString) ? true : ("false".equals(booleanString) ? false : null));
}

booleanString 不等于 true 而不是 false 我得到 NullPointerException.

是boxing/unboxing问题吗?

由于您正在 returning 对象类型 Boolean,然后 java 尝试将 return 值 null 拆箱为 boolean 原语输入一个逻辑表达式,其中 foo() 一直在使用。然后你得到空指针异常。

这里有一个类似的案例和我的解释:

你猜对了。对于正式的解释,答案在于 JLS:

If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.

因为你在两个表达式中都有基本的 truefalse,你的条件表达式的类型是 boolean

当你进入第二个表达式时,在第二种情况下,将空引用转换为布尔值 null.booleanValue();,导致 NPE,因此表达式等效于:

return Boolean.valueOf(null.booleanValue());

(然后表达式的return类型被重新装箱为Boolean,但如你所料,为时已晚)。

例如:

return ("true".equals(booleanString) ? Boolean.TRUE : ("false".equals(booleanString) ? Boolean.FALSE : null));

不会导致 NPE,因为表达式的类型是 Boolean。然而,这

return ("true".equals(booleanString) ? true : ("false".equals(booleanString) ? Boolean.FALSE : null));

导致它是因为同样的规则再次适用(因为第一个表达式是原始 boolean 类型)。所以它相当于:

return Boolean.valueOf(("true".equals(booleanString) ? true : ("false".equals(booleanString) ? Boolean.FALSE : null).booleanValue());