What is Type Erasure?

Type erasure is a process by which the Java compiler removes information about generic types from the bytecode of class files. This process was introduced in Java 5 alongside generics themselves. Implementing type erasure allowed Java to maintain backward compatibility without requiring the recompilation of Java 4 code.

Type erasure involves three main actions:
  1. If type parameters are bounded, the upper bound replaces the type parameter where used; otherwise, Object is used.
  2. Casting to the appropriate type is added wherever a generic type is assigned to a variable of a non-generic type.
  3. Bridge methods are generated.
More details about generic bounds and bridge methods will be discussed in subsequent posts.

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.
What is Type Erasure?