views:

1304

answers:

2

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.

+5  A: 

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?

Jon Skeet
No its not a Boolean instance but has value as true or false
Ravi Gupta
Then what type is it?
Matthew Flaschen
Thanks it did the trick. How lame I am :)
Ravi Gupta
I'm curious about what type is the variable... :)
helios
Assuming true / false are Strings you could use: boolean b = Boolean.parseBoolean(String.valueOf(someObject)); Be aware that this will return false for any String value other than "true" (case insensitive) and hence will return false if someObject is null.
Adamski
+2  A: 

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

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