Passing the Class<T> in java of a generic list?

Posted by Rob Stevenson-Leggett on Stack Overflow See other posts from Stack Overflow or by Rob Stevenson-Leggett
Published on 2010-05-09T14:23:55Z Indexed on 2010/05/09 14:28 UTC
Read the original article Hit count: 191

Filed under:
|

I have a method for reading JSON from a service, I'm using Gson to do my serialization and have written the following method using type parameters.

public T getDeserializedJSON(Class<T> aClass,String url)
{
    Reader r = getJSONDataAsReader(url);
    Gson gson = new Gson();
    return gson.fromJson(r, aClass);
}

I'm consuming json which returns just an array of a type e.g.

[
 { "prop":"value" }
 { "prop":"value" }
]

I have a java class which maps to this object let's call it MyClass. However to use my method I need to do this:

RestClient<ArrayList<MyClass>> restClient = new RestClient<ArrayList<MyClass>>();
ArrayList<MyClass> results = restClient.getDeserializedJSON(ArrayList<MyClass>.class, url);

However, I can't figure out the syntax to do it. Passing just ArrayList.class doesn't work.

So is there a way I can get rid of the Class parameter or how do I get the class of the ArrayList of MyClass?

© Stack Overflow or respective owner

Related posts about java

Related posts about generics