Test if object is instanceof a parameter type

Nikordaris picture Nikordaris · Apr 20, 2011 · Viewed 76.4k times · Source

Is there a way to determine if an object is an instance of a generic type?

public <T> test(Object obj) {
    if (obj instanceof T) {
        ...
    }
}

That clearly doesn't work. Is there an alternative? Like I want to use Java reflection to instantiate a class and then check to make sure it is of type generic T.

Answer

Mark Peters picture Mark Peters · Apr 20, 2011

The only way you can do this check is if you have the Class object representing the type:

Class<T> type; //maybe passed into the method
if ( type.isInstance(obj) ) {
   //...
}