[英]Class type reference not pass in java generic class or method
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? 现在的问题是,我从来没有在T中获得MyClass引用。我在哪里做错了? .
。 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. 我的问题是如何在T中获取MyClass引用。因为我需要使用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);
Generic type tokens don't work. 通用类型令牌无效。
You need to pass in the new TypeToken<List<MyClass>>() {}
as a constructor parameter to ServiceHandler
: 您需要将
new TypeToken<List<MyClass>>() {}
作为构造函数参数传递给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>() {});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.