Passing a class with type parameter as type parameter for generic method
in Java
Firstly, I find this problem a little hard to explain, so let me know if
I've left anything out, or whether I'm being a total numpty.
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>().class)
However we end up losing the generic type anyways, and merely get back an
ArrayList of unknown type (though it can be cast).
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.
No comments:
Post a Comment