什么是Type& TypeToken? [英] What is Type & TypeToken?
问题描述
我的项目中有以下方法
public void execute(final int apiId, final ResponseHandler handler, final Type type)
并使用TypeToken确定类型,如下所示
and the type is determined using TypeToken as follows
final Type serviceErrorType = new TypeToken<>() {
}.getType();
我经历了这个链接此处但无法完全理解类型
和 TypeToken
I went through this link here but couldn't understand completely about Type
and TypeToken
任何人都可以分享链接或帮助理解这两个概念吗?
Can anyone please share a link or help understand these two concepts?
推荐答案
来自链接:
强制客户端创建此类的子类,即使在运行时也可以检索类型信息。
Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.
让我们用例子说。
假设您要使用将JSON解析为Java类Gson 图书馆。
现在,您必须明确告诉Gson:
Assume you want to parse a JSON to Java class with Gson library. Now, you have to specifically tell Gson, that:
我希望将此JSON转换为列表 用户对象
您如何告诉Gson?如果它只是用户
,你可以告诉 User.class
。但是不可能说列表<用户> .class
How would you tell that to Gson? If it was only User
, you could tell User.class
. But it isn't possible to say List<User>.class
new Gson().fromJson(json, new TypeToken<List<User>>(){}.getType())
但是现在你可以准确地指定Gson应该将它转换为用户列表
。
But now you can specify precisely that Gson should convert it to a List of Users
.
应引用文档中的解释:
表示泛型类型
T
。 Java还没有提供表示泛型类型的方法,所以这个类有。
Represents a generic type
T
. Java doesn't yet provide a way to represent generic types, so this class does.
看看此博客文章了解有关该主题的更多详细信息。
Have a look at this blog post for more details on the topic.
这篇关于什么是Type& TypeToken?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!