How can I achieve this?
public class GenericClass
{
public Type getMyType()
{
//How do I return the type of T?
}
}
Here is 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
1. Has to be extended with typed class (Child extends Generic
)
OR
2. Has to be created as anonymous implementation (new Generic
)