DanielD DanielD - 1 year ago 134
Java Question

How to use java generics with restTemplate

I have an execute method that I've created where I pass in my restTemplate instance along with the class obj. However, I'm getting some warnings about unchecked types. I can't seem to figure out how to do this with generics. Here's what I have so far:

public class RepositoryUtils {

private static final Logger LOGGER = LoggerFactory.getLogger(RepositoryUtils.class);

public static ResponseEntity execute(String url, RestTemplate restTemplate, Class generic) {

LOGGER.info("GET: {}", url);

ResponseEntity response = null;
try {
response = restTemplate.exchange(url, HttpMethod.GET, RequestHelper.getGzipHttpEntity(), generic);
} catch (Exception e) {
LOGGER.error("RestTemplate: {} - {}", url, e.getMessage());

return response;

And here is how I make a call to my static execute:

ResponseEntity<Channels> response = RepositoryUtils.execute(channelUrlFinal, restTemplate, Channels.class);

Answer Source

Here is what you could try as signature of your method:

public static <T> ResponseEntity<T> execute(String url, RestTemplate restTemplate, 
    Class<T> generic) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download