简体   繁体   English

检查Object是否是String,HashMap或HashMap []的实例

[英]Check if Object is instance of String, HashMap, or HashMap[ ]

I have an Object in java. 我在java中有一个Object。 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? 有没有办法在将对象实际投射到这些对象之前检查对象是否是String,HashMap或HashMap []的实例?

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? 如果没有,因为上述方法似乎违反直觉,是否有办法将其投射到每个对象中,并测试一些关于新铸造的对象,看看它实际上是否是它所铸造的对象的类型?

Yes: 是:

 if(obj instanceof String)
 {
     String str = (String) obj;
     .
     .
     .
 }

By the way, to clarify regarding this: 顺便说一句,澄清一下:

[…] test something about the newly casted object to see if its in fact the type of object into which it was casted? [...]测试一些关于新铸造物体的东西,看看它实际上是否是它所铸造的物体的类型?

You cannot cast something into an invalid type. 无法将某些内容转换为无效类型。 If obj has type String , then ((Integer)obj) will cause a ClassCastException to be raised at run-time. 如果obj具有String类型,那么((Integer)obj)将导致在运行时引发ClassCastException

You are looking for the instanceof operator. 您正在寻找instanceof运算符。

The instanceof operator compares an object to a specified type. instanceof运算符将对象与指定的类型进行比较。 You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface. 您可以使用它来测试对象是否是类的实例,子类的实例或实现特定接口的类的实例。

Example: "Hello" instanceof String would return true while new Integer(5) instanceof String would return false . 示例: "Hello" instanceof String将返回truenew Integer(5) instanceof String将返回false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM