简而言之,我有一个变量,告诉我需要在对象上修改哪个属性,但是不能将该属性称为变量。
data class MyDataClass(var one: String, var two: Int)
fun doSomething() {
myData = MyDataClass("first", 2)
val propertyImInterestedIn = "one"
myData.{propertyImInterestedIn} = "second" // How do I do this?
assertEquals("second", myData.one)
}
答案 0 :(得分:2)
如果可以直接引用字段,则可以在编译时执行此操作,也可以在运行时执行,但会失去编译时的安全性:
// by referencing KProperty directly (compile-time safety, does not require kotlin-reflect.jar)
val myData = MyDataClass("first", 2)
val prop = myData::one
prop.set("second")
// by reflection (executed at runtime - not safe, requires kotlin-reflect.jar)
val myData2 = MyDataClass("first", 2)
val reflectProp = myData::class.memberProperties.find { it.name == "one" }
if(reflectProp is KMutableProperty<*>) {
reflectProp.setter.call(myData2, "second")
}
答案 1 :(得分:0)
您可以使用Kotlin反射API来做到这一点,尤其是bound callable references:
val propertyImInterestedIn = myData::one
propertyImInterestedIn.set("second")
请注意,您需要将kotlin-reflect
添加为项目的依赖项。