How to avoid compiler warnings when type information is not available?

I am using Spring RestTemplateto make calls against the REST web service. One of these calls is to return a list of objects of a particular type. Methods RestTemplaterequire a class argument 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 does not compile. You cannot get a static property .classwhen you provide such a type argument. The code compiles when I remove the type argument, but which generates a warning rawtypesfor the compiler.

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

+5
source share
2 answers

But how would RestTemplate know to convert list items into class instances Foo? Have you tried to run the code and does it work as expected?

One way that I can think of all this is to use an array as the input type. eg.

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

But I do not know if this was supported. If you really need to deserialize more complex data types, you should consider using Jackson or Gson.

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

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

, , TypeReference, , mapper Foo. .

+3

:

List<Class<Foo>> classList = new ArrayList<Class<Foo>>();
restTemplate.getForObject(restServiceURI, classList);

, , :

restTemplate.getForObject(restServiceURI, Foo.class);
0