简体   繁体   中英

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?

eg

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM