在Kotlin中创建Spring的ParameterizedTypeReference实例 [英] Create instance of Spring´s ParameterizedTypeReference in Kotlin
问题描述
我正在尝试学习Kotlin,并测试它在Spring Boot中如何工作.我的应用程序使用mongo数据库存储数据,并且我有一个Jersey资源来检索数据.我正在使用spring-boot-test
和RestTestTemplate
对其进行测试.
I am trying to learn Kotlin, and test how it works with spring boot. My application is using a mongo database to store data and I have a Jersey resource for retrieving data. I am testing it using spring-boot-test
and RestTestTemplate
.
RestTestTemplate
具有采用ParameterizedTypeReference
的exchange
方法.此类具有受保护的构造函数.因此,我从Kotlin设法使用它的唯一方法是:
The RestTestTemplate
has an exchange
method which takes a ParameterizedTypeReference
. This class has a protected constructor. So the only way I managed to use it from Kotlin was like this:
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}]")
}
}
这是正确的(或唯一的)方法吗?还是有更好的方法?
Is this the correct (or only) way to do this, or is there a better way?
If it helps, here is a link for the whole test: testclass on github
推荐答案
虽然使用对象表达式的答案是正确的,并且直接等效于您在Java中的处理方式,但是在需要大量代码的情况下,通过类型化的类型参数可以简化它ParameterizedTypeReference
s:
While the answer using object expression is correct and the direct equivalent of the way you do it in Java, reified type parameters allow you to simplify it if you need many ParameterizedTypeReference
s:
inline fun <reified T> typeReference() = object : ParameterizedTypeReference<T>() {}
// called as
restTemplate.exchange(requestEntity, typeReference<List<Person>>())
当编译器看到typeReference<SomeType>
调用时,它将被定义替换,因此结果与编写object : ParameterizedTypeReference<SomeType>() {}
相同.
When the compiler sees a typeReference<SomeType>
call, it's replaced by the definition, so the result is the same as if you wrote object : ParameterizedTypeReference<SomeType>() {}
.
这篇关于在Kotlin中创建Spring的ParameterizedTypeReference实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!