Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the {}.getType() syntax mean in Gson? [duplicate]

Tags:

java

json

gson

In the Gson docs, I ran across this construct to use for converting a list of JSONified Spotify Artist objects back into the ArrayList of objects. I use this in the onRestoreInstanceState().

However, I have never seen the {} after a declaration. Can someone explain to me what it means? I know that getType() is a member class but why the {}?

 Type type = new TypeToken<List<Artist>>() {}.getType();
 mArtistsList = new Gson().fromJson(jsonSearchResults, type);
like image 201
Kazinsky Avatar asked Sep 15 '25 17:09

Kazinsky


1 Answers

{} means an anonymous class that doesn't override any methods. Here's another anonymous class you've seen before:

Runnable r = new Runnable() {
   @Override
   public void run() {
   }
};

.getType() returns a java.lang.reflect.Type which Gson uses to identify which TypeAdapter it's going to use to serialize and deserialize your Object / JSON String.

See my answer here for more information on how Gson uses this to infer the generic type parameter; the short version is that it needs to use an anonymous class or it wouldn't work.

like image 139
durron597 Avatar answered Sep 18 '25 08:09

durron597