来自布尔的 NullPointerException

2022-01-19 00:00:00 boolean java nullpointerexception

这是我认为的 Java 纯粹主义者之一.我最近遇到了一个将字符串值自定义解析为布尔值的方法的问题.一个足够简单的任务,但由于某种原因,下面的方法在 null 情况下抛出 NullPointerException...

This is one for the java purists I think. I recently had an issue with a method to perform a custom parsing of String values to a Boolean. A simple enough task, but for some reason the method below was throwing a NullPointerException in the null case...

static Boolean parseBoolean(String s)
{
    return ("1".equals(s) ? true : ("0".equals(s) ? false : null));
}

该方法的返回类型是布尔值,那么为什么或如何抛出 NullPointerException?从调试到似乎异常是在嵌套的内联条件语句计算为 null 并将 null 返回到外部内联条件的点引发的,但我再次无法解释原因.

The return type for the method is Boolean so why or how can a NullPointerException be thrown? From debugging through it seems the exception is being thrown at the point where the nested in-line conditional statement evaluates to null and returns null to the outer in-line conditional, but again I can't explain why.

最终我放弃了,改写了如下方法,效果符合预期:

Eventually I gave up and rewrote the method as follows, which works as expected:

static Boolean parseBoolean(String s)
{
    if ("1".equals(s)) return true;
    if ("0".equals(s)) return false;

    return null;
}

以下代码介于两者之间,也可以按预期工作:

The following code is half way between the two and also works as expected:

static Boolean parseBoolean(String s)
{
    if ("1".equals(s)) return true;

    return "0".equals(s) ? false : null;
}

推荐答案

这也有效:

static Boolean parseBoolean(String s)
{
    return ("1".equals(s) ? Boolean.TRUE : ("0".equals(s) ? Boolean.FALSE : null));
}

所以你得到 NPE 的原因是由于自动装箱,因为在三元运算符中使用 boolean 会导致表达式的结果被视为 boolean.并且取消装箱 null 会导致 NPE.

So the reason you get an NPE is due to autoboxing because using boolean in the ternary operator causes the result of the expression to be treated as a boolean. And un-boxing of null causes an NPE.

相关文章