Using Kotlin reflection, I am trying to check the KClass of each parameter of a class's primary constructor.
Given a simple data class like this:
data class MyPerson(val name: String, val age: Int)
val modelClass = MyPerson::class
I get its primary constructor val primaryConstructor = modelClass.primaryConstructor
. For each parameter, I want to check its class (is it Kotlin.String, Kotlin.Int etc). Something like this:
for (param in primaryConstructor.parameters) {
when(param.type) {
is Kotlin.String -> // do string thing
is Kotlin.Int -> // do int thing
}
Unfortunately, this isn't valid code. I've tried param.type
, param.classifier
, param.type.jvmErasure
and others. The closest I've found is param.type.jvmErasure.qualifiedName
, which gives me a String with the fully qualified name of the KClass. But I really want the KClass.
Is this possible at all?
Aucun commentaire:
Enregistrer un commentaire