NullPointerException from Boolean

后端 未结 3 1330
独厮守ぢ
独厮守ぢ 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:22

    My suggestion? Don't return Boolean, return boolean and throw an exception:

    static boolean parseBoolean(String s)
    {
      if ("1".equals(s)) return true;
      if ("0".equals(s)) return false;
    
      throw new IllegalArgumentException(s + " is not a boolean value.");
    }
    

    Adopting an approach like the above will help avoid you accidentally referencing a null Boolean object.

    See the excellent answer from NilsH to see why your original method is throwing an exception.

提交回复
热议问题