I am not able to understand TypeToken
of Google\'s GSON
api\'s fromJson
method. Below code is very complex to understand for me...
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.