大佬请问一个问题,我有调用远程接口需求,将每个接口的返回封装成对象,统一写调用,代码片段如下:
public static <T> BaseResult<T> doQuery(BaseQuery query) throws Exception {
Request request = Request.create(query.url(), Request.METHOD.POST);
.....
Response resp = Sender.create(request).send();
String content = resp.getContent();
return Json.fromJson(new PType<BaseResult<T>>(){}, content);
}
使用代码片段:
BaseQuery<PagerData<School>> query = new SchoolPagerQuery<>()
BaseResult<PagerData<School>> result = Querier.doQuery(query);
if(result != null) {
PagerData<School> pagerData = result.getData();//此行报错
List<School> schoolList = pagerData.getItems();
for (School school : schoolList) {
System.out.println(school);
}
}
其中BaseResult中泛型用的层次较多,代码如下:
public static <T> BaseResult<T> doQuery(BaseQuery query) throws Exception {
Request request = Request.create(query.url(), Request.METHOD.POST);
.....
Response resp = Sender.create(request).send();
String content = resp.getContent();
return Json.fromJson(new PType<BaseResult<T>>(){}, content);
}
public class BaseResult<T> {
.... 其他非泛型属性
/**
* 返回结果
*/
private T data;
}
public class PagerData<E> {
private Integer total;
private Integer currentPage;
private Integer perPage;
private List<E> items;
}
public class School {
....其他常规属性
private SchoolAuth schoolAuth;
private SchoolExt schoolExt;
}
此代码运行后,返回的都是java.util.LinkedHashMap
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.limit.kindergarten.common.remote.dto.result.PagerData
想请教大佬,是否能实现自动装配泛型到正确的对象,如果可以应该如何写,衷心谢谢大佬