Reputation: 301
This is the method which call the generic class method.
ServiceHandler<MyClass> serviceHandler = new ServiceHandler<MyClass>();
List<MyClass> res = serviceHandler.genericGetAll("https://api.github.com/users/hadley/orgs", MethodTypes.GET.toString(), null);
Here is the generic class with generic method
public class ServiceHandler<T>{
public ServiceHandler() {
}
public List<T> genericGetAll(String destinationUrl, String method, HashMap<String, String> params) {
List<T> genericResponse = null;
String httpResponse = httpClient(destinationUrl, method, params);
genericResponse = createListResponseHandler(httpResponse);
return genericResponse;
}
private List<T> createListResponseHandler(String string_response) {
return gson.fromJson(string_response, new TypeToken<List<T>>() {
}.getType());
}
Now the problem is I never get the MyClass reference in T. Where I am doing wrong? . I have done lots of google but still not found the solution.
My question is how to get MyClass reference in T. Because I need to serialized the data using gson.
I have tried. But still no solution
List<MyClass> res = serviceHandler.<MyClass>genericGetAll("https://api.github.com/users/hadley/orgs", MethodTypes.GET.toString(), null);
Upvotes: 1
Views: 401
Reputation: 140318
Generic type tokens don't work.
You need to pass in the new TypeToken<List<MyClass>>() {}
as a constructor parameter to ServiceHandler
:
public class ServiceHandler<T> {
private final TypeToken<List<T>> typeToken;
public ServiceHandler(TypeToken<List<T>> typeToken) {
this.typeToken = typeToken;
}
// ...
private List<T> createListResponseHandler(String string_response) {
return gson.fromJson(string_response, typeToken.getType());
}
}
and instantiate using:
ServiceHandler<MyClass> serviceHandler =
new ServiceHandler<>(new TypeToken<MyClass>() {});
Upvotes: 2