如何将对象转换为布尔值?

如何将 Java 对象转换为布尔原语

我试了下面的方法,但是没有用

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

构造函数 Boolean (Object)未定义

请指示。

215434 次浏览

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