mardi 30 octobre 2018

Howto Replace TypeToken from Guava with Gson

I am currently trying to refactor a project to avoid having to use guava as a dependency. I was using it mainly for reflection related features, but in most case I could find an altenative.

However, there is one case left I cannot fix for now: I try to retrieve the class of a generic parameter of the current class.

It works fine using Guava since the Type returned by TokenType can be casted to Class.

Guava:

(Class<I>) new com.google.common.reflect.TypeToken<I>(getClass()) {}.getType();

I attempted to substitute this call using the TypeToken from Gson instead, but apparently the information about I is lost and there result of this call is a TypeVariable than is kept as a Class after executing:

Gson:

(Class<I>) com.google.gson.reflect.TypeToken<I>() {}.getType();

As far as I can tell the getClass() parameter is a clue to why context is not kept. When I use Guava with the same signature:

(Class<I>) com.google.gson.reflect.TypeToken<I>() {}.getType();

I get this error message:

java.lang.IllegalStateException: Cannot construct a TypeToken for a type variable.

You probably meant to call new TypeToken(getClass()) that can resolve the type variable for you. If you do need to create a TypeToken of a type variable, please use TypeToken.of() instead.

I see Gson also as a (package protected) constructor using a Type as argument.

Is there a way to obtain the class of a Generic Parameter using Gson only ?

N.B. : The question was also raised as a Github issue on the Gson Project





Aucun commentaire:

Enregistrer un commentaire