I have a generics class, Foo
. In a method of Foo
, I want to get the class instance of type T
, but I just can\'t call T.
Here is a working solution:
@SuppressWarnings("unchecked")
private Class getGenericTypeClass() {
try {
String className = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0].getTypeName();
Class> clazz = Class.forName(className);
return (Class) clazz;
} catch (Exception e) {
throw new IllegalStateException("Class is not parametrized with generic type!!! Please use extends <> ");
}
}
NOTES: Can be used only as superclass
Child extends Generic
)OR
new Generic() {};
)