I have a class that deserializes an ArrayList of generics with this function just as described in the first answer of this thread: Java abstract class function generic Type
public <T> ArrayList<T> arrayType(String data){
return g.fromJson(data, TypeToken.get(new ArrayList<T>().getClass()));
}
Eclipse asks me to cast TypeToken resulting in this (sinde the function fromJson needs a Type, not a TypeToken)
public <T> ArrayList<T> arrayType(String data){
return g.fromJson(data, (Type) TypeToken.get(new ArrayList<T>().getClass()));
}
As result I get this error:
java.lang.ClassCastException: com.google.gson.reflect.TypeToken cannot be cast to java.lang.reflect.Type
At the gson user manual they tell you this is the correct way of calling the function
Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
Collection<Integer> ints2 = gson.fromJson(json, collectionType);
and I can’t see what am I doing wrong (if it is a valid answer, why am I getting this cast error?)
Well you’re calling
TypeToken.get, which returns aTypeToken– not aType. in the example you’re showing which works, it’s usingTypeToken.getType(), which returns aType.So you could use:
… and that would return you a
Type, but it may not be what you actually want. In particular, due to type erasure that will return you the same type whateverTyou specify from the call site. If you want the type to really reflectArrayList<T>, you’ll need to pass the class into the method, although I’m not entirely sure where to go from there. (The Java reflection API isn’t terribly clear when it comes to generics, in my experience.)As an aside, I’d expect a method called
arrayTypeto have something to do with arrays, notArrayList.