[英]Pass the class type in generic method java
一个定义了TestJsonData的Interface类。
public interface ICasAuthentication {
<T> List<T> TestJsonData();
}
接口类的实现方法
public class CasAuthentication implements ICasAuthentication {
private IServiceHandler _iServiceHandler = null;
public CasAuthentication(ServiceHandler ServiceHandler) {
this._iServiceHandler = ServiceHandler;
}
public <T>List<T> TestJsonData() {
List<T> response = null;
return response = _iServiceHandler.<T>genericGetAll("https://api.github.com/users/hadley/orgs", MethodTypes.GET.toString(), null);
}
}
再次使用定义方法为genericGetAll的接口类
public interface IServiceHandler
{
<T>List<T> genericGetAll(String destinationUrl, String method, HashMap<String, String> params);
}
接口类的实现方法
public class ServiceHandler implements IServiceHandler {
public String response = null;
private static Gson gson = new Gson();
public ServiceHandler() {
}
通用响应不是类MyClass类型。 仍然无法引用类类型。 T类型仍然没有引用为Myclass类型
public <T> 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 <T> List<T> createListResponseHandler(String string_response) {
return gson.fromJson(string_response, new TypeToken<List<T>>() {
}.getType());
}
}
如果我在gson.fromJson(string_response, new TypeToken<List<MyClass>>()
。中对gson.fromJson(string_response, new TypeToken<List<MyClass>>()
进行硬编码,则无需硬编码就可以得到类类型,响应就像在图像中看到的那样。
下面的代码调用方法TestJsonData()。我已经添加了隐式类型,但仍然找不到解决方案
List<MyClass> res = _iCasAuthentication.<MyClass>TestJsonData();
下图显示了没有硬代码Myclass的响应值。
下图显示了带有硬代码Myclass的响应值。
如果省略显式设置类型参数,并且编译器无法推断出该参数,则默认为Object
。
为了明确设置它,您应该执行以下操作:
List<MyClass> res = callingMethod.<MyClass>createListResponseHandler("");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.