andre.ramaciotti
05/31/2019, 12:22 PMObjectMapper
). So I know that I need to pass the class as an argument. But then, I also need to specify the type T
when instantiating the generic base class. Is there a way of making the compiler infer any of the two?
data class ExamplePayload(val value: String, val otherValue: Int)
abstract class Worker<T : Any>(private val kclass: KClass<T>) {
private lateinit var objectMapper: ObjectMapper
fun handleMessage(message: String) {
val payload = objectMapper.readValue(message, kclass.java)
work(payload)
}
protected abstract fun work(payload: T)
}
// Here I need to specify ExamplePayload twice:
class ExampleWorker : Worker<ExamplePayload>(ExamplePayload::class) {
override fun work(payload: ExamplePayload) {
TODO("not implemented")
}
}
luke
05/31/2019, 12:44 PMT::class.java
if you inline the function and retify the T
? Something like here: https://stackoverflow.com/a/34463352andre.ramaciotti
05/31/2019, 12:50 PMhandleMessage
? The issue is that this is actually a @RabbitListener
, so the method itself is called from spring. I'm not sure much control I would have over itsam
05/31/2019, 12:56 PMabstract class Worker<T>
class WhatAmI : Worker<String>() {
val type = (this::class.java.genericSuperclass as ParameterizedType).actualTypeArguments[0]
}
fun main() {
println(WhatAmI().type)
}
andre.ramaciotti
05/31/2019, 1:46 PMAdrián
05/31/2019, 1:57 PMabstract class MyWorker<T : Any> {
private lateinit var objectMapper: ObjectMapper
abstract fun handleMessage(message: String)
inline fun <reified V : T> doWorkWithMessage(message: String) {
doWorkWithMessage(message, V::class.java)
}
fun <V : T> doWorkWithMessage(message: String, clazz: Class<V>) {
val payload = objectMapper.readValue(message, clazz)
work(payload)
}
protected abstract fun work(payload: T)
}
// Here I need to specify ExamplePayload twice:
class MyExampleWorker : MyWorker<ExamplePayload>() {
override fun handleMessage(message: String): Unit = doWorkWithMessage<ExamplePayload>(message)
override fun work(payload: ExamplePayload) {
TODO("not implemented")
}
}
sam
05/31/2019, 2:21 PM