Alex Stelmachonak
06/28/2022, 3:35 PMinterface HttpResponseBody {
val asString: String
inline fun <reified T : Any> asInstanceOf(format: BodyFormat): T =
when (format) {
BodyFormat.JSON -> jacksonObjectMapper().readValue(asString)
}
}
so I can utilize the jackson-kotlin support of reified type parameters to not pass class instance to the deserialization method and be able to use it like this
response.body.asInstanceOf<User>(BodyFormat.JSON)
But reified
only works in inline
functions and I can't inline the function in interface. I was looking for not ugly way to workaround that and have similar implementation in place. So far I found two ways of doing this:
1. Convert HttpResponseBody
to abstract class, so inline
and reified
are working.
2. Convert asInstanceOf
method to the extension method of the HttpResponseBody
interface.
Both are working, but doesn't fit nicely with my other codebase (which I probably need to refactor), but I wanted to ask may be I am missing some other solutions?mitch
06/28/2022, 9:50 PMinterface HttpResponseBody {
fun <T> instanceOf(bodyFormat: BodyFormat, clazz: Class<T>): T
}
inline fun <reified T> HttpResponseBody.instanceOf(bodyFormat: BodyFormat) = instanceOf(bodyFormat, T::class.java)
mitch
06/28/2022, 9:52 PMAlex Stelmachonak
06/28/2022, 9:57 PMreadValue
requires generic type to be reified
, which is not possible.
If I just do T::class.java
it kind of works, but looses the benefits of Kotlin classes additional runtime data. I.e. I can't just use data class without extra @JsonProperty
annotations.Alex Stelmachonak
06/28/2022, 9:58 PMDALDEI
07/02/2022, 8:26 AM