开发者

How to cast Object to boolean?

开发者 https://www.devze.com 2022-12-19 01:12 出处:网络
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();

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 cons开发者_StackOverflowtructor Boolean(Object) is undefined

Please advise.


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?


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

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


use the conditional operator "?" like this below:

int a = 1;   //in case you want to type 1 or 0 values in the constructor call 
Boolean b;   //class var.
b=(a>0?true:false);   //set it in the constructor body
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号