Hey everyone :wave: I am trying to create a gson ...
# getting-started
s
Hey everyone 👋 I am trying to create a gson type adapter to process the object after it is de-serialized, following the pattern described here, https://github.com/google/gson/tree/master/extras/src/main/java/com/google/gson/interceptors However, not getting the right approach to convert that impl to Kotlin . Specifically, using generic type on an interface and apply the interface to an annotation class. Could someone provide any ideas or hint to get this approach right. This is what I have got so far, https://gist.github.com/sushant-droid/a3b673f513717b43550950cbcc1307cb
Problem that I am running into is that I cant use a type for my interface which is passed as an argument to the annotation class so I tried to use
*
projection
Copy code
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
annotation class EmptyObjectValidator(val deserializer: KClass<out JsonPostDeserializer<*>>)
^ this enables me to use the concrete impl for any class with annotation, e.g
Copy code
@EmptyObjectValidator(FluffValidator::class)
data class Fluff(val blah: String = "")
and this is how the concrete impl might look like,
Copy code
class FluffValidator: JsonPostDeserializer<Fluff> {
    override fun postDeserialize(type: Fluff) {
        TODO("Not yet implemented")
    }
}
However, use of
*
projection type doesn’t allow me to call the interface method when called like this,
Copy code
val objectValidator = type.rawType.getAnnotation(EmptyObjectValidator::class.java) ?: return null
override fun read(`in`: JsonReader?): T {
    val result = delegate.read(`in`)
    val postDeserializer: JsonPostDeserializer<*> = objectValidator.deserializer.javaObjectType.newInstance()
    postDeserializer.postDeserialize(result)

    return result
}
it errors out when calling the method here
postDeserializer.postDeserialize(result)
e
on one hand, you can
Copy code
annotation class EmptyObjectValidator<T>(val deserializer: KClass<out JsonPostDeserializer<T>>)
@EmptyObjectValidator<Fluff>(FluffValidator::class)
instead of using a raw type in the annotation, but regardless I think your caller will need to perform an unchecked cast since
.getAnnotation
won't understand the generic there
👍 1