I've got this class:
public class A<T> {
protected T something = new T();
...
}
Of course new T()
is not possible. What can I do instead?
I must not change the code where the constructor of this class is called, because this is done via reflection.
Annother problem is how to get the Class object of a generic class. mymethod(A.class) worked, but now A has got the parameter T.
You can receive the T as a parameter of the constructor:
protected T something;
public A(T something) {
this.something = something;
}
Or, if the goal of A is to really create new T instances, then take a factory of T as an argument:
protected T something;
public A(Factory<T> somethingFactory) {
this.something = somethingFactory.newInstance();
}
Class<T>
can be viewed as a Factory<T>
, since it has a newInstance()
method, that invokes the public no-arg constructor. But a Factory<T>
could create new instances using something other than this constructor.
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