检查 Object 是否是 String、HashMap 或 HashMap[ ] 的实例
我在java中有一个对象。有没有办法在将对象实际转换为 String、HashMap 或 HashMap[ ] 之前检查它是否是 String、HashMap 或 HashMap[ ] 的实例?
如果没有,因为上面的方法似乎违反直觉,有没有办法将其转换为每个对象,并测试新转换的对象的某些内容,看看它是否实际上是它所转换的对象的类型?
I have an Object in java. Is there a way to check if an object is an instance of a String, HashMap, or HashMap[ ] before actually casting it to those objects?
If not, as it seems counterintuitive that the above would work, is there a way to cast it into each object, and test something about the newly casted object to see if its in fact the type of object into which it was casted?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的:
顺便说一下,澄清一下:
您不能将某些内容转换为无效类型。如果
obj
的类型为String
,则((Integer)obj)
将导致在运行时引发ClassCastException
-时间。Yes:
By the way, to clarify regarding this:
You cannot cast something into an invalid type. If
obj
has typeString
, then((Integer)obj)
will cause aClassCastException
to be raised at run-time.您正在寻找
instanceof
操作员。示例:
"Hello" instanceof String
将返回true
,而new Integer(5) instanceof String
将返回false
。You are looking for the
instanceof
operator.Example:
"Hello" instanceof String
would returntrue
whilenew Integer(5) instanceof String
would returnfalse
.