google gson fromjson() TypeToken

后端 未结 1 1419
粉色の甜心
粉色の甜心 2021-01-18 10:01

I am not able to understand TypeToken of Google\'s GSON api\'s fromJson method. Below code is very complex to understand for me...

相关标签:
1条回答
  • 2021-01-18 10:20

    TypeToken is a trick to obtain information about generics at runtime thanks to the fact that classes with fully specified generic superclasses make that data available through reflection.

    The GSON user guide has a section on serializing/deserializing generics here: https://github.com/google/gson/blob/master/UserGuide.md#TOC-Serializing-and-Deserializing-Generic-Types

    To specifically answer your question, it creates an anonymous object that captures the generics of TypeToken in its superclass data. That data is then extracted through reflection and packaged as a Type instance with getType() to avoid memory leaks due to the aforementioned anonymous class.

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