Kotlin 数据类:如果我在编译时不知道它的名称,如何读取它的值? [英] Kotlin data class: how to read the value of property if I don't know its name at compile time?

查看:26
本文介绍了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.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 数据类:如果我在编译时不知道它的名称,如何读取它的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆