Create instance of generic type in Java?

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

    Dunno if this helps, but when you subclass (including anonymously) a generic type, the type information is available via reflection. e.g.,

    public abstract class Foo {
    
      public E instance;  
    
      public Foo() throws Exception {
        instance = ((Class)((ParameterizedType)this.getClass().
           getGenericSuperclass()).getActualTypeArguments()[0]).newInstance();
        ...
      }
    
    }
    

    So, when you subclass Foo, you get an instance of Bar e.g.,

    // notice that this in anonymous subclass of Foo
    assert( new Foo() {}.instance instanceof Bar );
    

    But it's a lot of work, and only works for subclasses. Can be handy though.

提交回复
热议问题