简体   繁体   中英

Generics type erasure

I have the concept that in generics the type perimeter's type is decided at run time and since the data type of an object has to be decided at compile time that is why an error is given:

T obj = new T(); // error : unexpected Type  

basically it says i don't know the or i cannot decide the type of T currently(compile-time). Now in generics, i read in the book that whenever a generic file/class compiles, all the type perimeter information is erased and replaced by Object like this:

T obj = new T();

is replaced by:

Object obj = new Object();

Now if all the type peimeter information or type perimeter is replaced by Object then why the compiler does not compile the file and gave an error of unexpected type? Also if T is replaced by Object at compile time, does this Object gets replaced by our Type Pertimeter's type which is decided at runtime time? I don't think this happens(the Object class erasure) but still if that is not happening then what actually is happening during compile time and runtime in generics?

When you call new T() , T cannot be considered type information. What it is is a constructor, but since T is not a real type, there is no constructor.

At runtime, T will have some real type, but assigning an object of type Object might lead to a conflict.

Think about the method

T <T> getT() {
    return new T();
}

and then calling it

<String>getT() 

Now if new T() were to be replaced with new Object() , the method would return an Object when a String was expected.

As for why new T() is not replaced by new String() : A class is not guaranteed to have a public no args constructor, so such a constructor might not exist for a concrete class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM