Kotlin数据类:如果在编译时不知道属性名称,该如何读取属性的值? [英] Kotlin data class: how to read the value of property if I don't know its name at compile time?
本文介绍了Kotlin数据类:如果在编译时不知道属性名称,该如何读取属性的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果仅在运行时知道属性名称,如何读取Kotlin数据类实例中的属性值?
How can I read the value of property in a Kotlin data class instance if the property name is only known at runtime?
推荐答案
此处是从给定属性名称的类的实例读取属性的函数(如果找不到属性,则抛出异常,但是您可以更改行为):
Here is a function to read a property from an instance of a class given the property name (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.memberProperties
// 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
}
用法示例:
// 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
注意: org.jetbrains.kotlin:kotlin-reflect
依赖项是使用Kotlin反射所必需的.
Note: The org.jetbrains.kotlin:kotlin-reflect
dependency is required to use Kotlin reflection.
这篇关于Kotlin数据类:如果在编译时不知道属性名称,该如何读取属性的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文