Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Erasure in Java

Type erasure is supposed to erase all generic information... If this is the case how does a library like GSON use generics to determine what type to deserialize to?

e.g.

private Map<String,Date> tenordates;

This will deserialize to <String,Date> where as

private Map<Date,Date> tenordates;

will deserialize to <Date,Date>

so somehow its using the generic info at runtime.

like image 566
DD. Avatar asked Jan 17 '11 13:01

DD.


1 Answers

Type erasure does not erase all type information. It does not delete it from class, field, return type and parameter definitions. The type information in the following examples is retained:

public class Foo extends List<Bar> { ..}

private List<Foo> foos;

public List<Foo> getFoos() {..}

public void doSomething(List<Foo> foos) {..}

This is accesible via reflection - the java.lang.reflect.ParameterizedType. You can check whether a given Type is instanceof that class, cast to it and obtain the type information.

like image 191
Bozho Avatar answered Sep 25 '22 13:09

Bozho