Serialization of 3rd party subtyped classes at runtime in Kotlin

49 Views Asked by At

I am developing a library in Kotlin that defines an abstract class that will be subtyped by third parties. Furthermore these subtypes should be annotated by with a custom annotation of my property.

@Serializable
abstract class Base(val myProperty: String) { // -- I own this code
}

@MyCustomAnnotation
data class Derived(val a : String, val b : Double) : Base(Derived::class.simpleName!!!) {
I don't own this code. Implemented by third party.
}

By library requirement I have the need to serialize all these subtypes but I can't annotate them with @Serializable because it's not my code.

Would there be any way to avoid forcing third parties to put the @Serializable annotation on the Base subtypes? Would there be any solution implementing a custom serializer? Could I somehow use my @MyCustomAnnotation to automatically include the @Serializable annotation?

Translated with DeepL.com (free version)

I have read the kotlin.serialization documentation but I can't find anything for this case. It is always assumed that the subtypes are known

0

There are 0 best solutions below