How to cast Object to boolean?

给你一囗甜甜゛ 提交于 2019-12-17 21:57:39

问题


How can I cast a Java object into a boolean primitive

I tried like below but it doesn't work

boolean di = new Boolean(someObject).booleanValue();

The constructor Boolean(Object) is undefined

Please advise.


回答1:


If the object is actually a Boolean instance, then just cast it:

boolean di = (Boolean) someObject;

The explicit cast will do the conversion to Boolean, and then there's the auto-unboxing to the primitive value. Or you can do that explicitly:

boolean di = ((Boolean) someObject).booleanValue();

If someObject doesn't refer to a Boolean value though, what do you want the code to do?




回答2:


Assuming that yourObject.toString() returns "true" or "false", you can try

boolean b = Boolean.valueOf(yourObject.toString())


来源:https://stackoverflow.com/questions/2206598/how-to-cast-object-to-boolean

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