Create instance of generic type in Java?

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

    Think about a more functional approach: instead of creating some E out of nothing (which is clearly a code smell), pass a function that knows how to create one, i.e.

    E createContents(Callable makeone) {
         return makeone.call(); // most simple case clearly not that useful
    }
    

提交回复
热议问题