在Kotlin中,是否可以使用变量来调用方法或属性?
In Kotlin, is it possible to use a variable to call a method or property?
简而言之,我有一个变量告诉我我需要在对象上修改哪个 属性,但不能将那个 属性 称为变量。
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)
}
您可以使用 Kotlin 反射 API 来做到这一点,特别是 bound callable references:
val propertyImInterestedIn = myData::one
propertyImInterestedIn.set("second")
请注意,您需要将 kotlin-reflect
添加为项目的依赖项。
如果可以直接引用字段,则可以在编译时执行,也可以在运行时执行,但会失去编译时安全性:
// 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")
}
简而言之,我有一个变量告诉我我需要在对象上修改哪个 属性,但不能将那个 属性 称为变量。
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)
}
您可以使用 Kotlin 反射 API 来做到这一点,特别是 bound callable references:
val propertyImInterestedIn = myData::one
propertyImInterestedIn.set("second")
请注意,您需要将 kotlin-reflect
添加为项目的依赖项。
如果可以直接引用字段,则可以在编译时执行,也可以在运行时执行,但会失去编译时安全性:
// 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")
}