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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2206598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:44:43  来源:igfitidea点击:

How to cast Object to boolean?

javacastingprimitive

提问by Ravi Gupta

How can I cast a Java object into a boolean primitive

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

I tried like below but it doesn't work

我试过如下,但它不起作用

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

The constructor Boolean(Object) is undefined

构造函数 Boolean(Object) 未定义

Please advise.

请指教。

采纳答案by Jon Skeet

If the object is actuallya Booleaninstance, then just cast it:

如果该对象实际上是一个Boolean实例,则只需对其进行强制转换:

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,然后自动拆箱到原始值。或者你可以明确地做到这一点:

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

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

如果someObject不引用布尔值,您希望代码做什么?

回答by chburd

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

假设 yourObject.toString() 返回“true”或“false”,您可以尝试

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