Erasure and Restrictions on Generics
The information on generics is used by the compiler but is not available at runtime.
This is called type erasure.
Generics are implemented using an approach called type erasure : The compiler uses the generic type information to compile the code, but erases it afterward. Thus, the generic information is not available at runtime. This approach enables the generic code to be backward compatible with the legacy code that uses raw types.
The generics are present at compile time. Once the compiler confirms that a generic type is used safely, it converts the generic type to a raw type. For example, the compiler checks whether the following code in (a) uses generics correctly and then translates it into the equivalent code in (b) for runtime use. The code in (b) uses the raw type.
Restriction 1: Cannot Use
Restriction 2: Cannot Use
Restriction 3: A Generic Type Parameter of a Class Is Not Allowed in a Static Context
ExceptionClasses Cannot Be Generic
What is erasure? Why are Java generics implemented using erasure?
If your program uses
ArrayList<Date>, does the JVM load both of them?
Can you create an instance using new E() for a generic type E? Why
Can a method that uses a generic class parameter be static? Why?
Can you define a custom generic exception class? Why?