Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why the TypeToken construction in Gson is so weird?

When I use Gson to parse between object and json, the initialization of a TypeToken is so weird:

Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();

I just know this kind of format: new TypeToken<Collection<Integer>>().getType();, what's the braces in above for? Thanks in advance!

P.S. I've looked into the source code of TypeToken class, it is a class(not interface or abstract) and without any constructor, which means it uses no-parameter constructor as default.

P.S.2 When I delete the braces, it tell me that the constructor is not visible. When I looked inside the TypeToken class, this is the constructor:

  protected TypeToken() {
        this.type = getSuperclassTypeParameter(getClass());
        this.rawType = (Class<? super T>) $Gson$Types.getRawType(type);
        this.hashCode = type.hashCode();
  }

Why doesn't it just use public instead?

like image 321
Judking Avatar asked Mar 18 '13 14:03

Judking


People also ask

What is TypeToken in GSON?

Class TypeToken<T> Represents a generic type T . Java doesn't yet provide a way to represent generic types, so this class does. Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.

What is TypeToken in Kotlin?

object: is used in Kotlin to instantiate anonymous class instances which extend from the parent class. In other words, this part object: TypeToken(){} actually creates an anonymous class that is a child of TypeToken class.


1 Answers

'Weird' is not exactly a technical term. The class is defined in such a way as to force you to explicitly specify a generic parameter to be associated with a concrete instance of it. Because compiled Java classes retain information about their generic parameters that information then becomes available to framework libraries that require it.

That's the very purpose of a super type token.

like image 122
Perception Avatar answered Oct 20 '22 21:10

Perception