Create instance of generic type in Java?

后端 未结 27 3073
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  隐瞒了意图╮
    2020-11-21 06:45

    If you mean new E() then it is impossible. And I would add that it is not always correct - how do you know if E has public no-args constructor? But you can always delegate creation to some other class that knows how to create an instance - it can be Class or your custom code like this

    interface Factory{
        E create();
    }    
    
    class IntegerFactory implements Factory{    
      private static int i = 0; 
      Integer create() {        
        return i++;    
      }
    }
    

提交回复
热议问题