从布尔NullPointerException异常

从布尔NullPointerException异常

本文介绍了从布尔NullPointerException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个java的pruists我想。我最近曾与执行字符串值的自定义解析为布尔方法的问题。一个再简单不过的事,但由于某种原因,下面的方法是在空的情况下抛出一个NullPointerException异常...

 静态布尔parseBoolean(String s)将
{
    返回(1.equals(S)真(0.equals(S)假日期null)?);
}

该方法的返回类型是布尔为什么/如何一个NullPointerException异常被抛出?
从通过它调试似乎例外,在那里的嵌套于行条件语句的计算结果为空,在线有条件返回null外,该点被抛出,但我又无法解释为什么。

最后,我放弃了,并改写了方法如下,符合市场预期其作品:

 静态布尔parseBoolean(String s)将
{
    如果(1.equals(S))返回true;
    如果(0.equals(S))返回false;    返回null;
}

以下code是两个之间的一半,也按预期工作:

 静态布尔parseBoolean(String s)将
{
    如果(1.equals(S))返回true;    返回0.equals(S)?假:空;
}


解决方案

这也可以工作:

 静态布尔parseBoolean(String s)将
{
    返回(1.equals(多个)Boolean.TRUE:(0.equals(多个)Boolean.FALSE:?空));
}

所以原因,你得到一个NPE是由于自动装箱,因为三元运算符使用布尔导致前pression的结果被视为布尔。和的未拳击导致NPE。

This is one for the java pruists 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));
}

The return type for the method is Boolean so why/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;
}
解决方案

This also works:

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

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.

这篇关于从布尔NullPointerException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 01:24