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
}
}