Problem summary:
I would like to pass a class with a type parameter (such as ArrayList<SomeClass>, for example) to a generic method as a type parameter.
Let's say I have a method:
public static <T> T getGenericObjectFromJson(String json, Class<T> genericType){
// details unimportant, basically returns an object of specified type
return JsonParser.fromJson(json, genericType);
}
This method, of course, will work perfectly fine for any kind of class. I can call the method like so, for example:
getGenericObjectFromJson(jsonString, User.class)
The problem: I discovered I cannot do this:
getGenericObjectFromJson(jsonString, ArrayList<User>.class)
Syntactically, this is obviously invalid. However, I am not certain how I would even accomplish something like this. I can, of course, pass ArrayList.class, however the addition of the generic type makes it no longer syntactically valid, and I cannot think of a way around it.
The only direct solution has been something like this (which seems rather goofy):
getGenericObjectFromJson(jsonString, new ArrayList<User>().getClass())
However we end up losing the generic type anyways, and merely get back an ArrayList of unknown type (though it can be cast). Plus, unnecessarily instantiating an object.
My only solution thus far has been to wrap that method in a class that contains a generic type parameter which can be instantiated, like so:
public class JsonDeserializer<T>...
In this case, the getGenericObjectFromJson method will use the class's generic type.
The Question(s): Ultimately, I am curious why I cannot pass a class with a type parameter, AND whether there is a way to accomplish what I attempted to do.
As always, let me know if there are any problems with this question.
Classobject representing a constructed generic type. - cdhowieC#, nah just kidding. you can't do that due to "type erasure", which is what java does when you compile, by removing the generic type information - Federico BerasateguigetGenericArrayListFromJson(jsonString, User.class)? This is probably the best you're going to be able to do. - Jim Garrison