<分区>
我有以下返回语句:
public Boolean foo(String booleanString){
return ("true".equals(booleanString) ? true : ("false".equals(booleanString) ? false : null));
}
当 booleanString
不等于 true
且不等于 false
时,我得到了 NullPointerException
。
是装箱/拆箱问题吗?
<分区>
我有以下返回语句:
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.
因为您在两个表达式中都有原始的 true
和 false
,所以您的条件表达式的类型是 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/