如何将对象转换为布尔值?
如何将 Java 对象转换为布尔原语
我尝试如下,但它不起作用
boolean di = new Boolean(someObject).booleanValue();
构造函数 Boolean(Object) 未定义
请告知。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果对象实际上是一个
Boolean
实例,那么只需对其进行强制转换:显式强制转换将转换为
Boolean
,然后是自动-拆箱到原始值。或者您可以明确地执行此操作:如果
someObject
不引用布尔值,那么您希望代码执行什么操作?If the object is actually a
Boolean
instance, then just cast it: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:If
someObject
doesn't refer to a Boolean value though, what do you want the code to do?假设 yourObject.toString() 返回“true”或“false”,你可以尝试
Assuming that yourObject.toString() returns "true" or "false", you can try
使用条件运算符“?”像下面这样:
use the conditional operator "?" like this below: