why the TypeToken construction in Gson is so weird?

constructor, gson, java, json

Solution

'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.

Problem

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?

Original source