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?
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.
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.
'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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With