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
In Java 8 you can use the Supplier functional interface to achieve this pretty easily:
class SomeContainer {
private Supplier supplier;
SomeContainer(Supplier supplier) {
this.supplier = supplier;
}
E createContents() {
return supplier.get();
}
}
You would construct this class like this:
SomeContainer 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 bigIntegerContainer
= new SomeContainer<>(() -> new BigInteger(1));