Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a new object of a generic type?

Tags:

java

generics

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.

like image 860
yoooshi Avatar asked Dec 06 '22 16:12

yoooshi


1 Answers

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.

like image 115
JB Nizet Avatar answered Dec 19 '22 02:12

JB Nizet