小编典典

在Kotlin中创建Spring的ParameterizedTypeReference实例

spring-boot

我正在尝试学习Kotlin,并测试它如何在Spring
Boot中工作。我的应用程序使用mongo数据库存储数据,我有一个Jersey资源来检索数据。我正在使用spring-boot- test和测试RestTestTemplate

RestTestTemplate具有exchange这需要一个方法ParameterizedTypeReference。此类具有受保护的构造函数。因此,我从Kotlin设法使用它的唯一方法是:

class ListOfPeople : ParameterizedTypeReference<List<Person>>()

这是我的测试方法:

@Test
fun `get list of people`() {
    // create testdata
    datastore.save(Person(firstname = "test1", lastname = "lastname1"))
    datastore.save(Person(firstname = "test2", lastname = "lastname2"))
    datastore.save(Person(firstname = "test3", lastname = "lastname2"))
    datastore.save(Person(firstname = "test4", lastname = "lastname2"))

    val requestEntity = RequestEntity<Any>(HttpMethod.GET, URI.create("/person"))

    // create typereference for response de-serialization
    class ListOfPeople : ParameterizedTypeReference<List<Person>>() // can this be done inline in the exchange method?
    val responseEntity : ResponseEntity<List<Person>> = restTemplate.exchange(requestEntity, ListOfPeople())

    assertNotNull(responseEntity)
    assertEquals(200, responseEntity.statusCodeValue)
    assertTrue( responseEntity.body.size >= 4 )

    responseEntity.body.forEach { person ->
        println("Found person: [${person.firstname} ${person.lastname}] " +
                ", born [${person.birthdate}]")
    }
}

这是这样做的正确(或唯一)方法,还是有更好的方法?

如果有帮助,这里是整个测试的链接:github上的testclass


阅读 861

收藏
2020-05-30

共1个答案

小编典典

尽管使用对象表达式的答案是正确的,并且直接等效于您在Java中执行它的方式,但是如果需要多个ParameterizedTypeReferences
,则经过修饰的类型参数可以使您简化它:

inline fun <reified T> typeReference() = object : ParameterizedTypeReference<T>() {}

// called as
restTemplate.exchange(requestEntity, typeReference<List<Person>>())

当编译器看到typeReference<SomeType>调用时,它将被定义替换,因此结果与您编写的相同object : ParameterizedTypeReference<SomeType>() {}

2020-05-30