4

I am struggling trying to simplify my code. I have a common oppperation that makes a request to an API and gets a JSON object. This json can be Categories, Products etc. I am using jackson ObjectMapper.

Currently I have a method for each request, but I want to simplify it in one method. For example.

myMethod(String Path, Here The class Type)

One of this common methods is:

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;
}

The one thing that changes across all methods is the type of object to retrieve.

It is possible to generalize the line

Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<Category>>() {
        });

To be

Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<T>>() {
        });

I've tried to add as a param to the method Class<T> class, as shown here, but I get the error Cannot find symbol T

Community
  • 1
  • 1
Alejandro Alcalde
  • 5,990
  • 6
  • 39
  • 79

1 Answers1

1

I finally came up with a solution, here it is:

public static <T> List<T> getList(String url, Class<T> clazz) {

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet getRequest = new HttpGet(url);
    getRequest.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
    getRequest.setHeader(HttpHeaders.COOKIE, Login.getInstance().getToken());

    List<T> data = null;

    HttpResponse response;
    try {
        response = client.execute(getRequest);
        data = Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), Constants.JSON_MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
    } catch (IOException ex) {
        logger.error("Error retrieving  " + clazz.getName() + " " + ex.toString());
    }
    // TODO: Replace List<category> with Observable?
    return data;
}
Alejandro Alcalde
  • 5,990
  • 6
  • 39
  • 79
  • 3
    Is Generics really this horricially bad in JAVA? This would be a breeze in C#... I have the same issue now, unfortunately... – Ted Jul 25 '15 at 12:34