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  
}

build.gradle.kts

dependencies {
    implementation(kotlin("reflect"))
}

Using

// 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

Kotlin相关问答推荐

可以从背景图像中点击图标吗?

如何在Android应用判断上运行多个查询

S使用MAP和ElseThrow的习惯用法是什么?

Android Jetpack Compose:在空的 Compose 活动中找不到 OutlinedTextField (Material3)

为什么 trySend 会发出假数据?

Kotlin 数据类中的大量参数

我可以在 Kotlin 中使用接口类型作为构造函数参数吗

如何在 Kotlin 中实现 Composition UML 关系?

判断 AAR 元数据值时发现的一个或多个问题:

Android数据绑定在自定义视图中注入ViewModel

kotlin:扩展方法和空接收器

如何处理 Kotlin 中的异常?

Jetpack Compose – LazyColumn 不重组

如何使用kotlin中的反射查找包中的所有类

Kapt不适用于Android Studio 3.0中的AutoValue

RecyclerView SnapHelper无法显示第一个/最后一个元素

Android 上的 Kotlin:将map到list

Android Jetpack导航,另一个主机片段中的主机片段

如何启用spring security kotlin DSL?

如何在 IntelliJ IDEA 中禁用粘贴时将 Java 转换为 Kotlin?