Generic Erasure concept

后端 未结 1 1627
忘掉有多难
忘掉有多难 2021-01-17 09:27

Could you please help me to understand the generic concept here.

// Can\'t create an instance of T.
class Gen {
  T ob;

  Gen() {
    ob = new T();         


        
1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-17 09:57

    There are a few ways that may work out here:

    From a logical POV:
    It's not even guaranteed that whatever template-parameter T you use has a default-constructor. Which obviously offers the problem of how to handle the absence of a default-constructor. Possible solutions would be to produce a runtime-error, compile-time error or disallow any T that doesn't provide a default-constructor. The latter would obviously break the template-definition, which allows any T. And the runtime-error would complicate things quite a bit and yield the same problem as mentioned above. Remains preventing this behavior in the first place and throwing a compile-time error.

    From a internal view:
    Let's assume we could use the provided code. Then how would it work? Due to erasure, new T() would produce an Object. But what if T is Integer? Well, we're screwed. An Object is not an Integer, so we'll get a plain class-cast exception.

    So in summary: allowing the above to compile wouldn't work from a practical POV and in addition break the current definition of generics in java.

    0 讨论(0)
提交回复
热议问题