Different ways to check the type of an object in java?

I have an obj object and a class name MyClass , I can check if obj is of type MyClass using either instanceof, or I can say obj.getClass (). Equals ("MyClass"). So I want to know if there are other ways to check the type of an object.

+2


a source to share


7 replies


Beware: instanceof

Returns true also if your object is a subclass MyClass

, or if it implements an interface (this is usually what you're interested in - if you remember the concept of the "IS A" PMO)



See also about Class.isAssignableFrom()

, similar to instanceof

but slightly more powerful.

+2


a source


Please note that the two parameters you are citing are not equivalent:



"foo" instanceof Comparable // returns true
"foo".getClass().equals(Comparable.class) // return false

      

+2


a source


+1


a source


instanceof is another option.

0


a source


instancef

is not the correct solution as it gives true for the subclass of the class. Use this instead:

 obj.getClass().equals("MyClass")

      

0


a source


Perhaps you can go through obj.getClass().getSuperClass()

to get something similar to instanceof

.

0


a source


As others say, instanceof

does not have the same functionality as equals

.

At another point when it comes to this issue in code, using the Visitor- pattern is clean (though not the smallest in the line of code). A nice benefit is that after the UI has been set up for a set of classes, this can be reused in all other places that all / some / some different class extensions should handle.

0


a source







All Articles