There is a following situation:
A class is given, with a generic field in it. Is it possible to instantiate the field at runtime with an instance of T?
class Root<T>{
T var;
Root(){
//instantiate var with an instance of T here
}
}
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.
If you have a class which extends
Root<T>and sets the type parameter in itsextendsclause, then it’s possible to dig it out using getGenericSuperclass(). For example Guice uses this approach to provide type parameter information to the injected classes.Otherwise, the best bet is to pass a
Class<T>instance as constructor parameter and use it. This will also result in simpler code, though a bit more boilerplate for each instantiation of the class.