java 什么是类型和类型令牌?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43117731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:05:40  来源:igfitidea点击:

What is Type & TypeToken?

javaandroidjsongsontypetoken

提问by Android

I have the following method in my project

我的项目中有以下方法

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

and the type is determined using TypeToken as follows

类型是使用 TypeToken 确定的,如下所示

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

I went through this linkhere but couldn't understand completely about Typeand TypeToken

我在这里浏览了这个链接,但无法完全理解TypeTypeToken

Can anyone please share a link or help understand these two concepts?

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

回答by azizbekian

From the linkyou provided:

从您提供的链接

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

强制客户端创建此类的子类,即使在运行时也可以检索类型信息。

Let's speak with example.

让我们用例子说话。

Assume you want to parse a JSON to Java class with Gsonlibrary. Now, you have to specifically tell Gson, that:

假设您想使用Gson库将 JSON 解析为 Java 类。现在,您必须特别告诉 Gson:

I want this JSON to be translated to a Listof Userobjects

我想这个JSON被翻译成一个列表用户对象

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

你会怎么告诉 Gson 呢?如果只是User,你能看出来User.class。但不能说List<User>.class

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

But now you can specify precisely that Gson should convert it to a List of Users.

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

Should quote explanation from docs:

应该引用文档中的解释:

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

代表一个泛型类型T。Java 还没有提供表示泛型类型的方法,所以这个类提供了。

Have a look at this blog postfor more details on the topic.

有关该主题的更多详细信息,请查看此博客文章