Java class object from type variable

Alexander Temerev picture Alexander Temerev · May 10, 2010 · Viewed 25k times · Source

Is there a way to get Class object from the type variable in Java generic class? Something like that:

public class Bar extends Foo<T> {
    public Class getParameterClass() {
        return T.class; // doesn't compile
    }
}

This type information is available at compile time and therefore should not be affected by type erasure, so, theoretically, there should be a way to accomplish this. Does it exist?

Answer

sfussenegger picture sfussenegger · May 10, 2010

This works:

public static class Bar extends Foo<String> {
  public Class<?> getParameterClass() {
    return (Class<?>) (((ParameterizedType)Bar.class.getGenericSuperclass()).getActualTypeArguments()[0]);
  }
}