It can be done, but type erasure can make it very hard. As the other answers discuss, you either have to make a subclass of ParameterizedClass
or add a field of type T
to ParameterizedClass
, and the reflection code you need to do it is convoluted.
What I recommend in these circumstances, is to work around the issue like this:
class ParameterizedClass<T> {
private Class<T> type;
/** Factory method */
public static <T> ParameterizedClass<T> of(Class<T> type) {
return new ParameterizedClass<T>(type);
}
/** Private constructor; use the factory method instead */
private ParameterizedClass(Class<T> type) {
this.type = type;
}
// Do something useful with type
}
Due to Java's type inference for static methods, you can construct your class without too much extra boilerplate:
ParameterizedClass<Something> foo = ParameterizedClass.of(Something.class);
That way, your ParameterizedClass
is fully generic and type-safe, and you still have access to the class object.
EDIT: Addressed the comment