コードを単純化しようとして苦労しています。API にリクエストを送信し、JSON オブジェクトを取得する一般的な操作があります。これjson
はCategories
、Products
などの場合があります。私は jackson を使用していObjectMapper
ます。
現在、リクエストごとにメソッドを持っていますが、1 つのメソッドに簡略化したいと考えています。例えば。
myMethod(String Path, Here The class Type)
この一般的な方法の 1 つは次のとおりです。
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