Type erasure involves three main actions:
- If type parameters are bounded, the upper bound replaces the type parameter where used; otherwise,
Object
is used. - Casting to the appropriate type is added wherever a generic type is assigned to a variable of a non-generic type.
- Bridge methods are generated.
Type information is erased only from methods and fields but remains in the class's metadata. This information can still be accessed at runtime using reflection, specifically with
Field#getGenericType
method.A type with generic information erased is referred to as "Non-reifiable".
Type erasure enables Java to use generics without creating new classes for each application of a generic, unlike C++ templates, for instance.