Create instance of generic type in Java?

后端 未结 27 3574
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 06:14

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

27条回答
  •  萌比男神i
    2020-11-21 06:59

    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));
    

提交回复
热议问题