Reputation: 367
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?
Upvotes: 0
Views: 239
Reputation: 51030
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.
Upvotes: 1
Reputation: 425288
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.
Upvotes: 1
Reputation: 10103
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.
Upvotes: 4
Reputation: 66657
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
.
Upvotes: 3