Java boolean question

Status
Not open for further replies.

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by vafarmboy:
I need a simple way to take any type, object or primative and check its boolean value. Any suggestions? quickly if you can.

Sure. Figure out what you mean by "boolean value". Java's definition is "true is true, false is false, there are no other boolean values."

Statically, you cannot write:

code:<HR>
Code:
if (getAnyProperty()) ...

unless getAnyProperty returns boolean. And you cannot safely convert any other type to boolean. If getAnyProperty() really is any method at all with any return type at all, you could use reflection to invoke it, and you could use instanceof to check its type:

code:<HR>
Code:
Object ret = getClass().getMethod("getAnyProperty", new Class[] {})
               .invoke(this, new Object[] {});
if (ret instanceof Boolean) { ... }
else if (ret instanceof Integer) { ... }
else ...

Yuck. Yuck. Yuck.

for reference, I'm porting VB code that uses CBool()

I wouldn't want to do that.

(kg*m*m)/(s*s)
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by vafarmboy:
The closest I've come is

if(Boolean.valueOf(something.getProperty().toString()).booleanValue())

It's ugly, I know, and it doesn't work... The problem is you can't call 'toString()' on a primative.

I would think that the problem is that the only value that is true according to Boolean.valueOf(String) is the string "true" (disregarding case), and all others are false. Perhaps that's exactly what you want.

In that case, you can use two different tricks to turn a primitive value into a string:

code:<HR>
Code:
if (Boolean.valueOf(String.valueOf(something.getProperty())).booleanValue())

or

code:<HR>
Code:
if (Boolean.valueOf("" + something.getProperty()).booleanValue())

(kg*m*m)/(s*s)
 
Status
Not open for further replies.