Is it possible to create an instance of a generic type in Java? I\'m thinking based on what I\'ve seen that the answer is no (due to type erasure), but
If you need a new instance of a type argument inside a generic class then make your constructors demand its class...
public final class Foo {
private Class typeArgumentClass;
public Foo(Class typeArgumentClass) {
this.typeArgumentClass = typeArgumentClass;
}
public void doSomethingThatRequiresNewT() throws Exception {
T myNewT = typeArgumentClass.newInstance();
...
}
}
Usage:
Foo barFoo = new Foo(Bar.class);
Foo etcFoo = new Foo(Etc.class);
Pros:
Cons:
Fooproof. For starters... newInstance() will throw a wobbler if the type argument class does not have a default constructor. This does apply to all known solutions though anyway.