我有一个像这样的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")
我收到一个错误:
两者都不像这样:
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/