Check if the object is an instance of String, HashMap or HashMap []

I have an object in java. Is there a way to check if an object is an instance of String, HashMap, or HashMap [] before actually passing it to these objects?

If not, then it seems contradictory that the above would work, there is a way to drop it at each object and check something about the newly made object to see if its type of object is really different

+8
java casting types
source share
3 answers

Yes:

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

By the way, make this clear:

[& hellip;] check something about the newly made object to see if this is really the type of object to which it was added?

You cannot use something in an invalid type. If obj is of type String , then ((Integer)obj) will raise a ClassCastException at run time.

+26
source share

You are looking for instanceof operator.

The instanceof operator compares the object with the specified type. You can use it to check 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 will return true , and new Integer(5) instanceof String will return false .

+8
source share

Your design is suspected if you need to use instanceof . Are you checking if you have an array of String, HashMap or HashMap? Where is abstraction and information lurking in this?

Java is an object oriented language. I don’t know what problem you are solving, but it looks like you are lost. You should think of a better abstraction than that.

+2
source share

All Articles