Create instance of generic type in Java?

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

    Hope this's not too late to help!!!

    Java is type-safe, meaning that only Objects are able to create instances.

    In my case I cannot pass parameters to the createContents method. My solution is using extends unlike the answer below.

    private static class SomeContainer {
        E e;
        E createContents() throws Exception{
            return (E) e.getClass().getDeclaredConstructor().newInstance();
        }
    }
    

    This is my example case in which I can't pass parameters.

    public class SomeContainer {
        E object;
    
        void resetObject throws Exception{
            object = (E) object.getClass().getDeclaredConstructor().newInstance();
        }
    }
    

    Using reflection create run time error, if you extends your generic class with none object type. To extends your generic type to object convert this error to compile time error.

提交回复
热议问题