我的项目中有如下方法
public void execute(final int apiId, final ResponseHandler handler, final Type type)
并且类型是使用 TypeToken 确定的,如下所示
final Type serviceErrorType = new TypeToken<>() {
}.getType();
我经历了这个link here 但不能完全理解 Type
和 TypeToken
谁能分享一个链接或帮助理解这两个概念?
最佳答案
来自link你提供了:
Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.
让我们举个例子。
假设您要使用 Gson 将 JSON 解析为 Java 类图书馆。 现在,你必须明确地告诉 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有关该主题的更多详细信息。
关于java - 什么是类型和类型 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43117731/