I have a parameterized class :
class ParameterizedClass<T extends AbstractSomething> {
}
calling:
new ParameterizedClass<Something>();
So how can I get actual type Something of T
by using Java Generics?
In order to check the generic type, we need to create an instance of the generic class<T> and then we can compare the same with our class.
The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).
A Generic class can have muliple type parameters.
You can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With