简体   繁体   English

Java中的类型擦除

[英]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? 类型擦除应该擦除所有泛型信息...如果是这种情况,那么像GSON这样的库如何使用泛型来确定要反序列化为哪种类型?

eg 例如

private Map<String,Date> tenordates;

This will deserialize to <String,Date> where as 这将反序列化为<String,Date> ,其中

private Map<Date,Date> tenordates;

will deserialize to <Date,Date> 将反序列化为<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 . 这可以通过反射实现java.lang.reflect.ParameterizedType You can check whether a given Type is instanceof that class, cast to it and obtain the type information. 您可以检查给定的Type是否是该类的instanceof ,将其强制转换为该类并获取类型信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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