简体   繁体   中英

Java pass a list type to a generic method?

I have written the following method that takes a generic type. How do i pass a list of type Order as the response type?

public <T> ServiceResponse<T> fetchGet(String url, Class<T> responseType, boolean authRequired);

// This works just fine
fetchGet("MY_URL", Order.class, true);

// How do i pass a list?
fetchGet("MY_URL", List<Order>.class, true);

You're going to have to use List.class and do an explicit cast afterwards. Or you could do the alternate hack of calling fetchGet("MY_URL", (Class<List<Order>>) (Class) List.class, true); .

I ended up using an array instead of a list. I had to pass this to RestTemplate exchange method, and passing an array instead of List worked.

fetchGet("MY_URL", Order[].class, true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM