简体   繁体   中英

How can instantiate Class<T> from T?

I've got following method:

public <T> execute(HttpRequest request) {
   ...
   // in parseAs i have to pass Class<T> how can I instantiate it from T?
   request.execute().parseAs(classT);
}

PS: parseAs is method from google http client library .

You cannot with those parameters.

Java's generics use something called type erasure - basically all those T s become Object at runtime. So if you actually need to know what class this T is, you'll need a Class object to be passed in. This is exactly what parseAs is doing - to invoke parseAs<String> , you'd call parseAs(String.class) .

However, your execute has no Class parameter. As such, it has no idea what specialization it was invoked with, and cannot therefore pass that data on to parseAs .

The solution is to add a Class<T> parameter and punt to the next level up in the call chain, where the concrete type is (hopefully) known:

public <T> execute(Class<T> klass, HttpRequest request) {
   ...
   request.execute().parseAs(klass);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM