tags:

views:

62

answers:

7

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.

+1  A: 

Class#isAssignableFrom(java.lang.Class) is another option.

gpampara
A: 

instanceof is another option.

khotyn
+2  A: 

Note that the two options you cite are not equivalent:

"foo" instanceof Comparable // returns true
"foo".getClass().equals(Comparable.class) // return false
Michael Borgwardt
+1  A: 

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.

leonbloy
A: 
instancef is not proper solution as it gives true for subclass of a class.



 obj.getClass().equals("MyClass") it gives you the correct answer.
giri
A: 

You could probably recurse through obj.getClass().getSuperClass() to get something similar to instanceof.

Marcus Adams
A: 

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.

Lars Andren