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

标签 java boolean ternary-operator boxing unboxing

<分区>

我有以下返回语句:

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

booleanString 不等于 true 且不等于 false 时,我得到了 NullPointerException

是装箱/拆箱问题吗?

最佳答案

你猜对了。对于正式的解释,答案在于 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(); 将 null 引用转换为 boolean,导致 NPE,因此表达式等效于:

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

(然后表达式的返回类型被重新装箱为 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());

关于java - 当我使用三元运算符时抛出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30078984/

相关文章:

javascript - 可能会破坏我 Javascript 职业生涯的基本 boolean 逻辑

ruby - 三元评估是否需要参数化?

java - 在 Java 中生成 Antlr 解析器 : Not all inputs are read

Java HashMap 为什么返回 null?

java - 全局 OpenGL 纹理

java - 在java中的单个引用中调用不同类的不同方法

javascript - boolean 运算符如何工作 ||

mysql - 我可以在 1 列中保存 7 个 boolean 值吗?

c# - 完整的 if/else 语句与条件运算符

javascript - AngularJS 三元表达式无效