DD.
DD.

Reputation: 22011

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.

Upvotes: 6

Views: 433

Answers (1)

Bozho
Bozho

Reputation: 597342

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.

Upvotes: 5

Related Questions