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?
genericsjavareflection
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?
Best Solution
After type erasure, all that is known about
T
is 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.