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
Dunno if this helps, but when you subclass (including anonymously) a generic type, the type information is available via reflection. e.g.,
public abstract class Foo {
public E instance;
public Foo() throws Exception {
instance = ((Class)((ParameterizedType)this.getClass().
getGenericSuperclass()).getActualTypeArguments()[0]).newInstance();
...
}
}
So, when you subclass Foo, you get an instance of Bar e.g.,
// notice that this in anonymous subclass of Foo
assert( new Foo() {}.instance instanceof Bar );
But it's a lot of work, and only works for subclasses. Can be handy though.