What is Type & TypeToken?

后端 未结 1 1721
野的像风
野的像风 2020-12-29 04:12

I have the following method in my project

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

and the typ

相关标签:
1条回答
  • 2020-12-29 04:34

    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.

    0 讨论(0)
提交回复
热议问题