30

I need a method where i could pass on a parameter which i assume would be a Class (not sure though) and in that method, instanceof would be used to check if x is an instance of the passed Class.

How should i do that? I tried a few things but none worked.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Nicolas Martel
  • 1,641
  • 3
  • 19
  • 34

2 Answers2

65

How about this:

public boolean checker(Object obj) {
    return obj instanceof SomeClass;
}

or if SomeClass needs to be a parameter:

public boolean checker(Object obj, Class someClass) {
    return someClass.isInstance(obj);
}

or if you want the instance to be someClass and NOT an instance of a subclass of someClass:

public boolean checker(Object obj, Class someClass) {
    return someClass.equals(obj.getClass());
}
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • for completeness, both `obj` and `someclass` have to be checked if `null` or not – user1406062 Oct 07 '12 at 05:06
  • 1
    @HussainAl-Mutawa - I disagree. In the absence of a specification, the correct behaviour would be to let a NullPointerException occur when the methods are called with bad (i.e. `null`) arguments. – Stephen C Oct 07 '12 at 05:07
  • 1
    Note the difference between the 2nd and 3d variants: 3d returns true only when the type of `obj` is strictly `someclass`, and 2nd returns true also when `obj.getClass()` extends or implements `someclass`. – Alexei Kaigorodov Oct 07 '12 at 05:58
  • @AlexeiKaigorodov - yes ... that's what I said. – Stephen C Oct 07 '12 at 06:22
16

Use Class.isInstance(Object).

nneonneo
  • 171,345
  • 36
  • 312
  • 383