0

I use some nested classes like List, MyObject ...

Then I can find the type of them with using:

Type type = new com.google.gson.reflect.TypeToken<List<String>>() {}.getType();

But when I try to handle it with generic types like:

public static <T> T findClass(Class<T> resultClass)
    {
        //E.g. resultClass = String.class; Expect: List<String>
        Type type = new com.google.gson.reflect.TypeToken<List<T>>() {}.getType();
    }

It doesn't work for me.

In here, I wonder two things.

  1. Can I fix this problem?
  2. Can I describe a path like Class<List<String>> in java?
Sha
  • 921
  • 17
  • 46
  • 1
    No. If that was possible, there was no need for `TypeToken`. – Holger Feb 12 '20 at 16:53
  • If you know what the Type possible values are, you could always use `instanceof` to check the types against a known set of possible values – loganrussell48 Feb 12 '20 at 17:03
  • 2
    According to [this answer](https://stackoverflow.com/a/44303909/2711488), `TypeToken.getParameterized(List.class, resultClass).getType()` would work since Gson 2.8.0. – Holger Feb 13 '20 at 09:26

1 Answers1

0

According to @Holger's comment, I've just solved it like below:

public static <T> Set<T> fromJsonToSet(Class<T> resultClass)
{
    Type type = TypeToken.getParameterized(Set.class, resultClass).getType();
    ...
}
Sha
  • 921
  • 17
  • 46