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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
ParameterizedClassor add a field of typeTtoParameterizedClass, 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:
Due to Java’s type inference for static methods, you can construct your class without too much extra boilerplate:
That way, your
ParameterizedClassis fully generic and type-safe, and you still have access to the class object.EDIT: Addressed the comment