mojtab23 mojtab23 - 1 year ago 339
Java Question

Kotlin call java method with Class<T> argument

I want to use Spring

in Kotlin like this:

//import org.springframework.web.client.RestTemplate
fun findAllUsers(): List<User> {
val restTemplate = RestTemplate()

//has error
val ret = List<User>.javaClass
return restTemplate.getForObject(URI(hostAddress), ret)

RestTemplate.getForObject(URI url, Class<T> responseType)
has this signature and I get this error "unresolved reference List" from
val ret = List<User>.javaClass

If I use like this
val ret = List<User>
I get this error "Only classes are allowed on the left hand side of a class literal"

what's the problem? and what's the proper way for doing this? Is it a bug?

Answer Source

I think you need to actually use the RestTemplate.exechange method that has a signature that accepts a ParameterizedTypeReference<T> where T can be the generic type of your response (in your case a List<User>)

Suppose I have an endpoint that returns a list of Jedi names in JSON format, as follows


And I would like to invoke this endpoint and get a List<String> as the result, with the list containing the Jedi names from the JSON.

Then I can do this:

val endpoint = URI.create("")
val request = RequestEntity<Any>(HttpMethod.GET, endpoint)
val respType = object: ParameterizedTypeReference<List<String>>(){}
val response =, respType)
val items: List<String> = response.body;
println(items) //prints [Obi-wan, Luke, Anakin]

Notice that my ParameterizedTypeReference has a type argument of List<String>. That's what does the trick.

And that worked for me when I tried it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download