Create instance of generic type in Java? Create instance of generic type in Java? java java

Create instance of generic type in Java?


You are correct. You can't do new E(). But you can change it to

private static class SomeContainer<E> {    E createContents(Class<E> clazz) {        return clazz.newInstance();    }}

It's a pain. But it works. Wrapping it in the factory pattern makes it a little more tolerable.


I don't know 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<E> {  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 Fooassert( new Foo<Bar>() {}.instance instanceof Bar );

But it's a lot of work, and only works for subclasses. Can be handy though.


In Java 8 you can use the Supplier functional interface to achieve this pretty easily:

class SomeContainer<E> {  private Supplier<E> supplier;  SomeContainer(Supplier<E> supplier) {    this.supplier = supplier;  }  E createContents() {    return supplier.get();  }}

You would construct this class like this:

SomeContainer<String> stringContainer = new SomeContainer<>(String::new);

The syntax String::new on that line is a constructor reference.

If your constructor takes arguments you can use a lambda expression instead:

SomeContainer<BigInteger> bigIntegerContainer    = new SomeContainer<>(() -> new BigInteger(1));