Create instance of generic type in Java?

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

    Here is an option I came up with, it may help:

    public static class Container {
        private Class clazz;
    
        public Container(Class clazz) {
            this.clazz = clazz;
        }
    
        public E createContents() throws Exception {
            return clazz.newInstance();
        }
    }
    

    EDIT: Alternatively you can use this constructor (but it requires an instance of E):

    @SuppressWarnings("unchecked")
    public Container(E instance) {
        this.clazz = (Class) instance.getClass();
    }
    

提交回复
热议问题