问题
I noticed an issue with java.lang.Boolean class that it can not parse nulls. I know it has the parseBoolean static method but as it's signature states it only accepts String
and not an Object
.
In other words, it has the following signature:
public static boolean parseBoolean(String s)
but not:
Boolean.parseBoolean(Object)
What is the best way to check a Boolean value without falling on NullPointerException?
回答1:
Try that approach:
Boolean.TRUE.equals(yourObj);
回答2:
If you want your parse to return true
, false
or null
as a Boolean
object, take a look at Apache Commons Lang. BooleanUtils
has a one liner that does exactly this.
https://commons.apache.org/proper/commons-lang/javadocs/api-2.4/org/apache/commons/lang/BooleanUtils.html#toBooleanObject(java.lang.String)
BooleanUtils.toBooleanObject(null) == null
BooleanUtils.toBooleanObject("true") == true
BooleanUtils.toBooleanObject("false") == false
BooleanUtils.toBooleanObject("YES") == true
BooleanUtils.toBooleanObject("nO") == false
回答3:
You can compare it to Boolean.TRUE
or Boolean.FALSE
. Example:
if (Boolean.TRUE == Box.modeled()) {
//do somthing
}
来源:https://stackoverflow.com/questions/34895627/java-parse-boolean-that-may-be-null-to-boolean