Search code examples
javagenericsreflectiongeneric-collections

How do I avoid compiler warnings when generic type information is unavailable?


I'm using Spring's RestTemplate to make calls against a REST web service. One of these calls is to return a list of objects of a certain type. The RestTemplate methods require that a class argument be supplied to indicate the expected return type.

// restTemplate is type org.springframework.web.client.RestTemplate
URI restServiceURI = new URI("http://example.com/foo")
restTemplate.getForObject(restServiceURI, List<Foo>.class);

Obviously, this doesn't compile. You cannot get a static .class property when you supply the type argument like that. The code compiles when I remove the type argument, but that generates a rawtypes compiler warning.

My question is simple. Am I stuck with suppressing the compiler warning or is there a cleaner way to code for this?


Solution

  • But how would the RestTemplate know to convert the list elements to instances of class Foo? Have you tried running the code, and does it work as expected?

    One way I can think of getting round this would be to use an Array as an input type. eg.

    restTemplate.getForObject(restServiceURI, Foo[].class);
    

    But I don't know if that's supported. If you really need to deserialise more complex data types then you should consider using Jackson or Gson.

    With Jackson you can use the ObjectMapper class to easily deserialise data from most sources.

    String input = ...;
    ObjectMapper mapper = new ObjectMapper();
    List<Foo> list = mapper.readValue(input, new TypeReference<List<Foo>>(){});
    

    The above works because you intentionally create an anonymous class that extends TypeReference, the class will remember its generic types at runtime and so it can help the object mapper to create lists of Foo. For a fuller explanation.