Kotlin call java method with Class argument

前端 未结 4 691
忘了有多久
忘了有多久 2021-02-04 01:39

I want to use Spring RestTemplate in Kotlin like this:

//import org.springframework.web.client.RestTemplate
fun findAllUsers(): List {
          


        
4条回答
  •  不思量自难忘°
    2021-02-04 02:06

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

    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 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(HttpMethod.GET, endpoint)
    val respType = object: ParameterizedTypeReference>(){}
    val response = restTemplate.exchange(request, respType)
    val items: List = response.body;
    println(items) //prints [Obi-wan, Luke, Anakin]
    

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

    And that worked for me when I tried it.

提交回复
热议问题