gpt4 book ai didi

java - Gson TypeToken 是如何工作的?

转载 作者:IT老高 更新时间:2023-10-28 20:45:37 25 4
gpt4 key购买 nike

我知道在 Java 中与 C# 泛型相反,例如,C# 泛型是编译时特性,并且通过类型删除被删除。那么,Gson 的 TypeToken 究竟是如何工作的呢?它如何获取对象的泛型类型?

最佳答案

It's a trick!

From §4.6 of the JLS (强调我的):

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:

The erasure of a parameterized type (§4.5) G is |G|.

The erasure of a nested type T.C is |T|.C.

The erasure of an array type T[] is |T|[].

The erasure of a type variable (§4.4) is the erasure of its leftmost bound.

The erasure of every other type is the type itself.

因此,如果您声明一个具有其自身匿名子类的类,它会保持其参数化类型;它没有被删除。因此,请考虑以下代码:

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,因为删除;父类(super class)不是参数化类型,而是 Object

关于java - Gson TypeToken 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30005110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com