什么是类型和类型令牌?

What is Type & TypeToken?

我的项目中有如下方法

 public void execute(final int apiId, final ResponseHandler handler, final Type type)

并且使用TypeToken确定类型如下

final Type serviceErrorType = new TypeToken<>() {
    }.getType();

我在这里 link 看了一遍,但不能完全理解 TypeTypeToken

任何人都可以分享 link 或帮助理解这两个概念吗?

根据您提供的link

Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.

举个例子来说吧

假设您要使用 Gson 库将 JSON 解析为 Java class。 现在,你必须明确地告诉 Gson:

I want this JSON to be translated to a List of User objects

你会如何告诉 Gson?如果只是 User,你可以判断 User.class。但是不可能说 List<User>.class

new Gson().fromJson(json, new TypeToken<List<User>>(){}.getType())

但现在您可以精确指定 Gson 应将其转换为 List of Users

应该引用文档中的解释:

Represents a generic type T. Java doesn't yet provide a way to represent generic types, so this class does.

查看 this blog post 了解有关该主题的更多详细信息。