Inquisitive Idiot
Inquisitive Idiot

Reputation: 432

Can I turn a type parameter into a Class in Java?

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?

Upvotes: 0

Views: 93

Answers (1)

user2357112
user2357112

Reputation: 282198

Nope. By the time the method is executed, the type parameter has been erased. No information about type parameters is stored at runtime or baked into the bytecode at compile time; for example, the compiler does not secretly add an extra argument to your method and pass in Foo.class at the call site. You have to pass the Class yourself.

Upvotes: 2

Related Questions