I have got a template class as follows:
class MyClass<T> { T field; public void myMethod() { field = new T(); // gives compiler error } }
How do I create a new instance of T in my class?
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.
After type erasure, all that is known about
Tis that it is some subclass ofObject. You need to specify some factory to create instances ofT.One approach could use a
Supplier<T>:Usage might look like this:
Alternatively, you can provide a
Class<T>object, and then use reflection.