Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 809
Android Avatar asked Mar 30 '17 12:03

Android


People also ask

What do you mean by type?

type. [ tīp ] n. A number of people or things having in common traits or characteristics that distinguish them as a group or class. The general character or structure held in common by a number of people or things considered as a group or class.

What is an example of type?

The definition of a type means people, places or things that share traits which allow them to belong to the same group. An example of type is men with blond hair. Printed or typewritten characters; print. Let's see how your letter looks in type.

What is the meaning of type in computer?

1. To type or typing means to input characters into a computer using a keyboard.

What is type and kind?

Sort, type and kind all generally mean the same thing. They are words we use to refer to a group of people or things which share the same characteristics. We use these words very often when we describe things and we often find them in dictionary definitions: Jazz isn't the sort of music I can listen to for very long.


1 Answers

From the link you 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 Gson library. Now, you have to specifically tell Gson, that:

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

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()) 

But now you can specify precisely that Gson should convert it to a 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.

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

like image 89
azizbekian Avatar answered Sep 23 '22 10:09

azizbekian