Create instance of generic type in Java?

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

    You can achieve this with the following snippet:

    import java.lang.reflect.ParameterizedType;
    
    public class SomeContainer {
       E createContents() throws InstantiationException, IllegalAccessException {
          ParameterizedType genericSuperclass = (ParameterizedType)
             getClass().getGenericSuperclass();
          @SuppressWarnings("unchecked")
          Class clazz = (Class)
             genericSuperclass.getActualTypeArguments()[0];
          return clazz.newInstance();
       }
       public static void main( String[] args ) throws Throwable {
          SomeContainer< Long > scl = new SomeContainer<>();
          Long l = scl.createContents();
          System.out.println( l );
       }
    }
    

提交回复
热议问题