在Kotlin中,是否可以使用变量来调用方法或属性? [英] In Kotlin, is it possible to use a variable to call a method or property?

查看:383
本文介绍了在Kotlin中,是否可以使用变量来调用方法或属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之,我有一个变量,告诉我需要在对象上修改哪个属性,但是不能将该属性称为变量.

Simply put, I have a variable that tells me which property I need to modify on an object, but cannot call that property AS the variable.

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)
}

推荐答案

如果可以直接引用字段,则可以在编译时执行;或者在运行时执行,但会失去编译时的安全性:

You can either do it at compile time if You can directly reference the fields, or at runtime but you will lose compile-time safety:

// 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")
}

这篇关于在Kotlin中,是否可以使用变量来调用方法或属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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