gpt4 book ai didi

reflection - Kotlin 数据类 - 通过变量访问属性以设置其值

转载 作者:行者123 更新时间:2023-12-02 12:53:42 24 4
gpt4 key购买 nike

我有一个像这样的 Kotlin 数据类:

data class User(
var id: Int,
var name: String? = null,
var email: String? = null,
var age: Int? = null,
var latitude: Float? = null,
var longitude: Float? = null
)

然后我创建它的实例
var user = User(1)

然后我试试这个:
val field = "name"
var prop = User::class.memberProperties.find {it -> it.name == field}!!
prop.get(user)

它可以工作,但是如果我尝试像这样设置值:
prop.setter.call(user, "Alex")

我收到一个错误:

Unresolved reference: setter



它既不是这样工作的:
prop.set(user, "Alex")

(这是基于此处提供的解决方案,但它不适用于我: solution)

最佳答案

memberProperties返回 Collection<KProperty1<T, *>> , 但你需要 KMutableProperty1 .所以

if (prop is KMutableProperty1) {
(prop as KMutableProperty1<T, Any>).set(user, "Alex")
} else {
// what do you want to do if the property is immutable?
}

类型转换是必需的,因为智能类型转换只会给你一个 KMutableProperty1<T, *>你不能调用 set无论如何,因为编译器不知道接受什么类型作为它的第二个参数。

关于reflection - Kotlin 数据类 - 通过变量访问属性以设置其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54782505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com