Java generics type erasure: when and what happens?

Type erasure applies to the use of generics. There’s definitely metadata in the class file to say whether or not a method/type is generic, and what the constraints are etc. But when generics are used, they’re converted into compile-time checks and execution-time casts. So this code:

List<String> list = new ArrayList<String>();
String x = list.get(0);

is compiled into

List list = new ArrayList();
String x = (String) list.get(0);

At execution time there’s no way of finding out that T=String for the list object – that information is gone.

… but the List<T> interface itself still advertises itself as being generic.

EDIT: Just to clarify, the compiler does retain the information about the variable being a List<String> – but you still can’t find out that T=String for the list object itself.

Leave a Comment