Java: instanceof Generic

someguy picture someguy · Jan 16, 2011 · Viewed 50.5k times · Source

Isn't there any way to find the class-type of a generic?

if (T instanceof String) {
    // do something...
}

The above definitely does not compile.

Answer

Peter Lawrey picture Peter Lawrey · Jan 16, 2011

Generics are a compile time feature. Generics add checks at compile time which may not have any meaning at runtime. This is one example. You can only check the type of the object referenced which could be a super type in code. If you want to pass the type T you have do this explicitly.

void someMethod(Class<T> tClass) {
    if(String.class.isAssignableFrom(tClass)) 

or

void someMethod(Class<T> tClass, T tArg) {

Note: the type might not be the same,

someMethod(Number.class, 1);