The information on generics is used by the compiler but is not available at runtime.
This is called type erasure.
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.
Examples
Restions
-
Restriction 1: Cannot Use
new E()
-
Restriction 2: Cannot Use
new E[]
-
Restriction 3: A Generic Type Parameter of a Class Is Not Allowed in a Static Context
-
Restriction 4:
Exception
Classes Cannot Be Generic
Questions
-
What is erasure? Why are Java generics implemented using erasure?
-
If your program uses
ArrayList<String>
andArrayList<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?
-