I have an object obj and a class name MyClass, i can check whether obj is of the type MyClass using either instanceof or i can say obj.getClass().equals("MyClass"). So i want to know are there any other ways of checking the type of an object.
Note that the two options you cite are not equivalent:
"foo" instanceof Comparable // returns true
"foo".getClass().equals(Comparable.class) // return false
Beware: instanceof
returns true also if your object is a subclass of MyClass
, or if it implements the interface (this is usually what you are interested in - if you recall the "IS A" OOP concept)
See also this about Class.isAssignableFrom()
, similar to instanceof
but a little more powerful.
instancef is not proper solution as it gives true for subclass of a class.
obj.getClass().equals("MyClass") it gives you the correct answer.
You could probably recurse through obj.getClass().getSuperClass()
to get something similar to instanceof
.
As said by others, instanceof
does not have the same functionality as equals
.
On another point, when dealing with this problem in code, using a Visitor-pattern is a clean (although not smallest in lines of code) solution. A nice advantage is that once a visitor-interface has been setup for a set of classes, this can be reused again in all other places that need to handle all/some/one different extensions of a class.