I have a server that can return a few different kinds of objects, and I'm using GSON's fromJson to try and deal with it. So I want to write a method that sends a GET to the server and parses the result as an object of the right type. Basically I want to be able to do
Foo foo = getStuff("foo_url");
or
Bar[] bars = getStuff("bar_url");
and have it just work. So here's what I got so far (the "get" function is defined elsewhere and sends an HTTP GET request to the given URL and returns the response):
<T> T getStuff(String url) throws IOException {
CloseableHttpResponse response = get(url);
String body = EntityUtils.toString(response.getEntity());
response.close();
return gson.fromJson(body, /* ???? */);
}
So I need to replace the /* ???? */ with a Class object that represents T so that getStuff will give me back a T. It didn't work to just put T
in there, nor did new Class<T>().class
, so I'm out of hacks.
Can I do this?