我正在努力简化我的代码。我有一个常见的 oppperation 向 API 发出请求并获取 JSON 对象。这json
可以是Categories
等Products
。我正在使用杰克逊ObjectMapper
。
目前我对每个请求都有一个方法,但我想用一种方法来简化它。例如。
myMethod(String Path, Here The class Type)
这种常见的方法之一是:
public List<Category> showCategories() {
HttpClient client = HttpClientBuilder.create().build();
HttpGet getRequest = new HttpGet(Constants.GET_CATEGORY);
getRequest.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
getRequest.setHeader(HttpHeaders.COOKIE, Login.getInstance().getToken());
List<Category> data = null;
HttpResponse response;
try {
response = client.execute(getRequest);
data = Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<Category>>() {
});
} catch (IOException ex) {
LOGGER.error("Error retrieving categories, " + ex.toString());
}
// TODO: Replace List<category> with Observable?
return data;
}
在所有方法中发生变化的一件事是要检索的对象的类型。
可以概括这条线
Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<Category>>() {
});
成为
Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<T>>() {
});
我尝试将作为参数添加到方法Class<T> class
中,如此处所示,但出现错误Cannot find symbol T