Wednesday, December 14, 2005

Erasures in Java 1.5

..., the generics implementation uses a technique known as erasure. The easiest way to understand erasure is to think of the compiler as performing two distinct tasks. First, it does type checking at compile time using all the type information it has (including the type parameters). Then it transforms the code, using a set of rules that remove all of the type parameters (e.g. all of the parameterized types are mapped to raw types), and inserts a set of casting operations. The complete list of transformations is beyond the scope of this article. However, to give you an idea of what erasure does, here are some of the rules:

  • If a class doesn't use type parameters in its definition, erasure doesn't change the class definition.
  • Parameterized types "drop" their type parameters.
  • Every type parameter is mapped to the appropriate bound. By this, I mean: the type parameter is erased and replaced with the strongest type the compiler can reasonably assert. Thus, in the case of , T is mapped to Object. In the case of , T is mapped to Rentable, and so on.
  • Casts are inserted wherever necessary, to ensure that the code compiles.
(from link)

No comments: