java Parse Boolean that may be null to Boolean

冷暖自知 提交于 2020-01-16 06:38:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!