Create instance of generic type in Java?

后端 未结 27 3155
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  -上瘾入骨i
    2020-11-21 06:48

    There are various libraries that can resolve E for you using techniques similar to what the Robertson article discussed. Here's an implemenation of createContents that uses TypeTools to resolve the raw class represented by E:

    E createContents() throws Exception {
      return TypeTools.resolveRawArgument(SomeContainer.class, getClass()).newInstance();
    }
    

    This assumes that getClass() resolves to a subclass of SomeContainer and will fail otherwise since the actual parameterized value of E will have been erased at runtime if it's not captured in a subclass.

提交回复
热议问题