Kotlin 数据类 : how to read the value of property if I don't know its name at compile time?

标签 kotlin data-class

如果属性名称仅在运行时已知,我如何读取 Kotlin 数据类实例中的属性值?

最佳答案

这是一个从给定属性名称的类的实例中读取属性的函数(如果未找到属性则抛出异常,但您可以更改该行为):

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"))
}

使用

// 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 数据类 : how to read the value of property if I don't know its name at compile time?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35525122/

相关文章:

java - 无法获取 org.gradle.api.internal.artifacts.dsl.dependency.DefaultDependencyHandler 类型的对象的未知属性 'implementation'

android - 无法使用Moshi在Retrofit中为类创建@Body转换器

kotlin - 在 kotlin 中从 GSON 生成对象时不调用数据类初始化函数

generics - 使用 Kotlin 在通用接口(interface)中嵌套数据类

kotlin - 在 Kotlin 密封类之外引用?

generics - 可空运算符在泛型类中有效吗?

kotlin - 惯用地传递可空类型的方法引用

android - 如何在 RxJava 流中间有条件地添加异步操作?

Kotlin:密封类不能 "contain"数据类?为什么?

kotlin - 如何检查 Kotlin 数据类中的属性数量?