简体   繁体   中英

Java Generics- type erasure?

If I have a subclass which extends MySuperClass and I have the following generic class:

public class GenericClass<M extends MySuperClass>{

    public void aMethod(M m);

}

public class SubClass1 extends MySuperClass{}

then I do:

SubClass1 sc1 = new SubClass1();

GenericClass<MySuperClass> msc = new GenericClass<MySuperClass>();

msc.aMethod(sc1);

is is type erasure which determines whether the parametized type is legal? I presume the compiler can look at M extends MySuperClass , look at and determine its legal- but I wasnt sure if type erasure handled this?

Type erasure refers to the fact that the generic type parameters and instantiations are removed after the compilation. The compiler checks the types at compile time and then deletes all the type parameters.

Compiler is the one which make sure about type safety based on generic definition in code.

Type erasure removes them while compilation and

Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded

.

Type-safety is something that is ensured by the compiler. The only job of the type erasure is to erase the generics portion to make the code backwards compatible with the legacy codes which were written before the generics showed up in Java. So, it's the compiler that makes sure your code is syntactically correct whether it's relation to generics or not, before the erasure comes into action.

Type erasure is a runtime artefact, when all classes are effectively "raw" (untyped).

Generics exist only during compilation. The compiler checks that the generic parameter is within bounds, but the compiled bytecode has no type information.

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