mojtab23 mojtab23 - 2 months ago 20
Java Question

Kotlin call java method with Class<T> argument

I want to use Spring

RestTemplate
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)
}


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

If I use like this
val ret = List<User>::class.java
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

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

["Obi-wan","Luke","Anakin"]

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("http://127.0.0.1:8888/jedi.json")
val request = RequestEntity<Any>(HttpMethod.GET, endpoint)
val respType = object: ParameterizedTypeReference<List<String>>(){}
val response = restTemplate.exchange(request, 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.