It can be done, but type erasure can make it very difficult. Like the other answers, you either have to subclass ParameterizedClass , or add a field of type T to ParameterizedClass , and the reflection code you need to do is collapsed.
What I recommend in these circumstances is to work around the problem as follows:
class ParameterizedClass<T> { private Class<T> type; public static <T> ParameterizedClass<T> of(Class<T> type) { return new ParameterizedClass<T>(type); } private ParameterizedClass(Class<T> type) { this.type = type; }
Due to Java type inference for static methods, you can create your class without an extra template:
ParameterizedClass<Something> foo = ParameterizedClass.of(Something.class);
Thus, your ParameterizedClass fully versatile and type safe, and you still have access to the class object.
EDIT : Comment Address
jqno
source share