Gson TypeToken 是如何工作的? [英] How does Gson TypeToken work?
问题描述
我知道在 Java 中,例如,C# 泛型是编译时特性,并且通过类型擦除被删除.那么,Gson 的 TypeToken
究竟是如何工作的呢?它如何获取对象的泛型类型?
I understand that in Java contrary to, for example, C# generics are compile-time feature and is removed via type erasure. So, how does Gson's TypeToken
really work? How does it get the generic type of an object?
推荐答案
来自 JLS 的 §4.6(强调我的):
类型擦除是从类型(可能包括参数化类型和类型变量)到类型(从不参数化类型或类型变量)的映射.我们写|T|对于T类型的擦除,擦除映射定义如下:
Type erasure is a mapping from types (possibly including parameterized types and type variables) to types (that are never parameterized types or type variables). We write |T| for the erasure of type T. The erasure mapping is defined as follows:
参数化类型 (§4.5) G 的擦除是 |G|.
The erasure of a parameterized type (§4.5) G is |G|.
嵌套类型 T.C 的擦除是 |T|.C.
The erasure of a nested type T.C is |T|.C.
数组类型 T[] 的擦除是 |T|[].
The erasure of an array type T[] is |T|[].
类型变量的擦除(第 4.4 节)是擦除其最左边的边界.
The erasure of a type variable (§4.4) is the erasure of its leftmost bound.
所有其他类型的擦除是类型本身.
因此,如果您声明一个类具有其自身的匿名子类,它会保持它的参数化类型;它没有被删除.因此,请考虑以下代码:
Therefore, if you declare a class with an anonymous subclass of itself, it keeps it's parameterized type; it's not erased. Therefore, consider the following code:
import java.lang.reflect.ParameterizedType;
import java.util.Arrays;
import java.util.HashMap;
public class Erasure<T>
{
public static void main(String...strings) {
Class<?> foo = new Erasure<HashMap<Integer, String>>() {}.getClass();
ParameterizedType t = (ParameterizedType) foo.getGenericSuperclass();
System.out.println(t.getOwnerType());
System.out.println(t.getRawType());
System.out.println(Arrays.toString(t.getActualTypeArguments()));
}
}
输出:
null
class Erasure
[java.util.HashMap<java.lang.Integer, java.lang.String>]
注意如果你没有匿名声明类,你会得到一个ClassCastException
,因为擦除;超类不是参数化类型,而是 Object
.
Notice that you would get a ClassCastException
if you did not declare the class anonymously, because of erasure; the superclass would not be a parameterized type, it would be an Object
.
这篇关于Gson TypeToken 是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!