2

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.

bragboy
  • 34,892
  • 30
  • 114
  • 171
GuruKulki
  • 25,776
  • 50
  • 140
  • 201

7 Answers7

2

Note that the two options you cite are not equivalent:

"foo" instanceof Comparable // returns true
"foo".getClass().equals(Comparable.class) // return false
Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
2

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.

Community
  • 1
  • 1
leonbloy
  • 73,180
  • 20
  • 142
  • 190
1

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

gpampara
  • 11,989
  • 3
  • 27
  • 26
0

instanceof is another option.

khotyn
  • 944
  • 1
  • 8
  • 16
0

instancef is not proper solution as it gives true for subclass of a class. Use this instead:

 obj.getClass().equals("MyClass")
walther
  • 13,466
  • 5
  • 41
  • 67
giri
  • 26,773
  • 63
  • 143
  • 176
0

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

Marcus Adams
  • 53,009
  • 9
  • 91
  • 143
0

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
  • 8,601
  • 7
  • 41
  • 56