0 votes
1 view
in Java by (3.1k points)

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 I'd be interested if anyone can see something I'm missing:

class SomeContainer<E>

{

    E createContents()

    {

        return what???

    }

}

1 Answer

0 votes
by (22.4k points)

You are right, you can't do new E(). However, in Java 8, you can apply the Supplier functional interface to accomplish this pretty easily:

class SomeContainer<E> {

  private Supplier<E> supplier;

  SomeContainer(Supplier<E> supplier) {

    this.supplier = supplier;

  }

  E createContents() {

    return supplier.get();

  }

}

You would make this class like this:

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

The syntax String::new on that thread is a constructor citation.

If your constructor uses arguments you can use a lambda expression alternatively:

SomeContainer<BigInteger> bigIntegerContainer

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

...