How do I get the `.class` attribute from a generic type parameter?

前端 未结 3 1971
星月不相逢
星月不相逢 2021-02-03 16:44

The accepted answer to this question describes how to create an instance of T in the Generic class. This involves passing in a Class<

3条回答
  •  日久生厌
    2021-02-03 17:25

    If you're using the GSON library, you can get the type of T easily by using TypeToken. The class documentation is available here:

    I did it like this:

    This is my class definition:

    public class ManagerGeneric  {}
    

    This is in my method:

    // Get the type of generic parameter
    Type typeOfT = new TypeToken(){}.getType();
    // Deserialize
    T data = gson.fromJson(json, typeOfT);
    

提交回复
热议问题