2

I'm try to do something like this

public void method(Object obj, Class objClass) {
    if(obj instanceof objClass) {
        //do something
    }
}

I want to pass Class object or class name and test if that is and instanceof of that. This don't work, anyone know how to do this? Thanks

Mustafa
  • 931
  • 1
  • 13
  • 26
  • Or http://stackoverflow.com/questions/376988/is-there-any-way-other-than-instanceof-operator-for-object-type-comparison-in-ja – skaffman Mar 08 '12 at 17:56

1 Answers1

6

You can use the isInstance method of Class.

Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.

So you would write

if (objClass.isInstance(obj)) ...

If you want to do this generically, you can use .cast to convert to the type represented by objClass.

public <T> void method(Object obj, Class<T> objClass) {
  if(objClass.isInstance(obj)) {
    T t = objClass.cast(obj);
    //do something with t instead of obj
  }
}
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245