1

Recently, I'm learning about JSON, using Google's Gson. And I come across a problem. Here is code:

Type type = new TypeToken<Collection<Data>>(){}.getType();

I can't understand what {} really mean.So I read source code, and get class description like: Constructs a new type literal. Derives represented class from type parameter... Clients create an empty anonymous subclass. anonymous subclass really make me confused? Can anyone explain it concretely?

liaoming
  • 153
  • 3
  • 10
  • Are you asking about the type token or about anonymous classes in general? – Savior Apr 22 '16 at 16:59
  • Here's an explanation of the type token "hack": http://stackoverflow.com/questions/22271779/is-it-possible-to-use-gson-fromjson-to-get-arraylistarrayliststring – Savior Apr 22 '16 at 17:11

1 Answers1

8

The {} is the body of an anonymous class.

If you wanted to make it more readable, this is what it could look like:

class MyTypeToken extends TypeToken<Collection<Data>> { }
TypeToken<Collection<Data>> tcd = new MyTypeToken();
Type type = tcd.getType();

Here is a breakdown of the more succinct shorthand you have used:

Type type =
    new TypeToken<Collection<Data>>() { // this will initialise an anonymous object
        /* in here you can override methods and add your own if you need to */

    }   /* this ends the initialisation of the object. 
           At this point the anonymous class is created and initialised. */

    .getType(); // here you call a method on the object

I prefer using this:

TypeToken<Collection<Data>> tt = new TypeToken<Collection<Data>>(){ };
Type type = tt.getType();

One more thing I want to mention is that anonymous classes do not have the same class type as other anonymous classes which inherit from the same parent.

So if you have the following:

TypeToken<Collection<Data>> tt1 = new TypeToken<Collection<Data>>(){ };
TypeToken<Collection<Data>> tt2 = new TypeToken<Collection<Data>>(){ };

tt1.getClass() == tt2.getClass() will never be true.

smac89
  • 39,374
  • 15
  • 132
  • 179