lundi 6 mars 2023

How to create a new instance Serializable class by reflection in Kotlin?

Stub object for testing purposes fails to create via reflection:

internal fun <T : ParentThingy> KClass<in T>.random(): T {
    val createViaConstructor = constructors.first()
    val args = createViaConstructor.parameters.associateWith { param ->
        when (param.type) {
            Int::class.starProjectedType -> gen.primitive().int()
            // other options omitted for brevity
            else -> error("$param not supported, it's type ${param.type}")
        }
    }

    @Suppress("UNCHECKED_CAST")
    return createViaConstructor.callBy(args) as T
}

becase of:

parameter #2 serializationConstructorMarker of fun `<init>`(kotlin.Int, kotlinx.serialization.internal.SerializationConstructorMarker?): some.child.Thingy not supported, it's type kotlinx.serialization.internal.SerializationConstructorMarker?

-- the class has @Serializable annotation. Reflection with a factory method works fine. Any ideas how to make reflection work with a primary constructor?





Aucun commentaire:

Enregistrer un commentaire