JVM Type Erasure

When Java introduced generics in 1.5, it introduced them using type erasure. While the compiler knows a distinction between a List<String> and a List<Object>, there is no distinction at runtime.

There are two questions you can ask about this decision:

  1. Was it a good idea at the time, as a way of introducing generics into the language without too much of a cost.
  2. Whether or not it was necessary, does type erasure cause problems? How severe?

I'm a mild reified generics sceptic, but mostly undecided.

The Java Tutorials | Type Erasure

A readable introduction, explaining what type erasure is, what actual type information is contained in the classes produced by the compiler, how bridge methods are created, and what heap pollution is.

Puzzling Through Erasure

2004 era discussion of why generics were implemented using type erasure.

Reified Generics for Java

One of the more detailed proposals for adding reified generics to Java, with tradeoffs described.

Questioning the Reality of Generics

Brief overview of how generics are implemented in Java/on the JVM, and argues that for a polyglot VM, type erasure is a good choice because it doesn't constrain future languages. I don't know what types would be at issue--if a type can be instantiated in the JVM, can't it be the type of a reified generic? Is the problem something to do with expressing type bounds in reified generics?

Type Erasure is Good

Cites Wadler, "Theorems for Free", and explains the value of parametric polymorphism. However, I'm unclear whether there's a real connection between type erasure and parametricity. Some uses of reified generics violate parametricity, but since the JVM supports reflection, does not having reifed generics actually change anything for the better?

I sympathize with the motivating idea that the "right" way to use generics is to just use them as a compile time phenomenon, and avoid shenanigans that rely on runtime type information. I suspect that this is also why functional languages like Haskell and SML typically use type erasure. However, while I think this mental model blunts the perceived need for reified generics, I don't think it in any way requires type erasure.

Heap

HN Comments on Lambdas

Discussion of how lambdas might interact with type erasure. Not sure I understand it yet.

Adding Generics to the Java Programming Language: Public Draft Specification, Version 2.0

Java ™ Generics and Collections: Tools for Productivity

Wadler and Naftalin presentation on generics, including advantages and disadvantages of erasure. Mentions stubs, surface genericization and wrappers for accomodating old code with new generic classes.