How can I read the value of property in a Kotlin data class instance if the property name is only known at runtime?
How can I read the value of property in a Kotlin data class instance if the property name is only known at runtime?
下面是一个函数,用于从给定属性名称(throws exception if property not found, but you can change that behaviour)的类的实例中读取属性:
import kotlin.reflect.KProperty1
import kotlin.reflect.full.memberProperties
@Suppress("UNCHECKED_CAST")
fun <R> readInstanceProperty(instance: Any, propertyName: String): R {
val property = instance::class.members
// don't cast here to <Any, R>, it would succeed silently
.first { it.name == propertyName } as KProperty1<Any, *>
// force a invalid cast exception if incorrect type here
return property.get(instance) as R
}
dependencies {
implementation(kotlin("reflect"))
}
// some data class
data class MyData(val name: String, val age: Int)
val sample = MyData("Fred", 33)
// and reading property "name" from an instance...
val name: String = readInstanceProperty(sample, "name")
// and reading property "age" placing the type on the function call...
val age = readInstanceProperty<Int>(sample, "age")
println(name) // Fred
println(age) // 33