NullPointerException from Boolean

后端 未结 3 1351
独厮守ぢ
独厮守ぢ 2021-01-08 00:26

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

3条回答
  •  耶瑟儿~
    2021-01-08 01:08

    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.

提交回复
热议问题