Create instance of generic type in Java?

后端 未结 27 3099
佛祖请我去吃肉
佛祖请我去吃肉 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:53

    When you are working with E at compile time you don't really care the actual generic type "E" (either you use reflection or work with base class of generic type) so let the subclass provide instance of E.

    Abstract class SomeContainer
    {
    
        abstract protected  E createContents();
        public doWork(){
            E obj = createContents();
            // Do the work with E 
    
         }
    }
    
    
    BlackContainer extends SomeContainer{
        Black createContents() {
            return new  Black();
        }
    }
    

提交回复
热议问题