1

I have a confusion on Gson TypeToken.getParameterized method.

When I pass a Primitive type on typeArguments, Gson will throw an IllegalArgumentException. Then I use TypeToken anonymous inner class instead and there is no exception will be thrown.

Checking the Gson source code and find that ParameterizedTypeImpl will check typeArguments is Primitive:


static void checkNotPrimitive(Type type) {
  checkArgument(!(type instanceof Class<?>) || !((Class<?>) type).isPrimitive());
}

public ParameterizedTypeImpl(..., Type... typeArguments) {
  ...
  checkNotPrimitive(this.typeArguments[t]);
  ...
}

So why Gson TypeToken designed as it? Thank you.

ZSpirytus
  • 339
  • 2
  • 10
  • Hi If you are asking about design concepts, I suggest you go directly to [consult](https://github.com/google/gson/issues) the team, the information will be more accurate – Ian Aug 27 '21 at 03:33
  • Well, no need to bother the Gson team. You have to read how generics work in Java, and why primitives are not (yet) allowed: https://stackoverflow.com/questions/2721546/why-dont-java-generics-support-primitive-types , then you'll see that this "issue" unrelated to Gson per se. If you try using primitives in `TypeToken` parameterization directly, `javac` will not compile it throwing `Type argument cannot be of primitive type`, just like Gson does not let you to specify a primitive parameterization. – terrorrussia-keeps-killing Aug 27 '21 at 06:10
  • Thank you @lan, I try to get an answer at stackoverflow to avoid bothering Gson team by this simple problem(I think..). – ZSpirytus Aug 27 '21 at 08:31
  • Thank you @fluffy! Do you mean that: The type erasure make all generic be Object type and if we pass int.class (not a instance of Object) in typeArguments, int can not be cast Object, which is a contradiction. To avoid this case happen, Gson not allow passing a primitive type while calling TypeToken.getParameterized. – ZSpirytus Aug 27 '21 at 09:09
  • @ZSpirytus `The type erasure make all generic be Object` -- yes, with certain exceptional cases. ` int can not be cast Object,` -- yes, because `int` must be first boxed to `java.lang.Integer`. – terrorrussia-keeps-killing Aug 27 '21 at 10:38
  • @fluffy Sorry for slow response, thank you for solving my doubts! – ZSpirytus Aug 30 '21 at 03:19

0 Answers0