Create instance of generic type in Java?

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

    If you want not to type class name twice during instantiation like in:

    new SomeContainer(SomeType.class);
    

    You can use factory method:

     SomeContainer createContainer(Class class); 
    

    Like in:

    public class Container {
    
        public static  Container create(Class c) {
            return new Container(c);
        }
    
        Class c;
    
        public Container(Class c) {
            super();
            this.c = c;
        }
    
        public E createInstance()
                throws InstantiationException,
                IllegalAccessException {
            return c.newInstance();
        }
    
    }
    

提交回复
热议问题