4

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.

skayred
  • 10,603
  • 10
  • 52
  • 94

1 Answers1

4

You cannot with those parameters.

Java's generics use something called type erasure - basically all those Ts 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);
}
bdonlan
  • 224,562
  • 31
  • 268
  • 324
  • Though note this only works if T is not itself a parameterized type. It can be Integer but not List, for example. (The code will compile just fine, but there's no way to get a value of type Class> so it won't be useful.) – jacobm Nov 04 '11 at 05:04
  • What about this public void execute(HttpRequest request, AjaxListener callback) still impossible without additional class variable? – skayred Nov 04 '11 at 05:05
  • @skayred, nope! The `` vanishes at runtime, and it becomes `execute(HttpRequest request, AjaxListener callback)` – bdonlan Nov 04 '11 at 05:06
  • @skayred, it should also be noted that some other languages avoid this problem - notably, .NET (C# etc) and C++ do _not_ perform type erasure. Java does this because it needed to remain compatible with libraries built before generics were introduced. – bdonlan Nov 04 '11 at 05:07
  • @skayred, also, `execute(HttpRequest request, AjaxListener callback, Class klass)` would make it possible. – bdonlan Nov 04 '11 at 05:07
  • Yep, I know that C# provide a better support of generics – skayred Nov 04 '11 at 05:13