What is Type & TypeToken?

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

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

I looked at this link here, but couldn't fully understand Type and TypeToken

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

+5
source share
1 answer

From the link you provided:

It forces clients to subclass this class, which allows you to retrieve type information even at runtime.

Let's talk with an example.

Suppose you want to parse the JSON class for Java using Gson . Now you must tell Gson that:

I want this JSON to be translated into a List of User Objects

How would you say this to Gson? If it was only User , you could say User.class . But you can't say List<User>.class

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

But now you can specify exactly what Gson should convert it to List of Users .

An explanation of the documents should be indicated:

Represents a generic type T Java does not yet provide a way to represent generic types, which is why this class does.

Check out this blog post for more information on this topic.

+7
source

Source: https://habr.com/ru/post/1266121/


All Articles