Create instance of generic type in Java?

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

    Here's an implementation 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 approach only works if SomeContainer is subclassed so the actual value of E is captured in a type definition:

    class SomeStringContainer extends SomeContainer
    

    Otherwise the value of E is erased at runtime and is not recoverable.

提交回复
热议问题