如何在Kotlin中获取变量的名称?

Har*_*eet 3 variable-names kotlin delegated-properties

我的应用程序中有一个带有许多属性的Kotlin类,我想构建的是一种将变量名存储在字典中的方法。字典看起来像这样:

HashMap<String, Pair<Any, Any>>()
Run Code Online (Sandbox Code Playgroud)

这样做的目的是存储对特定属性所做的更改,我将变量的名称存储为键,在对中存储旧值和新值。为了通知更改,我使用观察者模式。因此,每当从属性调用设置器时,都会通知更改并将其存储到字典中。

以下代码导致以下问题:

var person = Person("Harry", 44)
person.age = 45
Run Code Online (Sandbox Code Playgroud)

HashMap("age", (44, 45))

现在,我只是将变量名硬编码为字符串,所以我的问题是:

如何在Kotlin中动态获取变量名?

我在Java中看到了相同的问题:Java思考:如何获取变量的名称?

另外,关于同一主题的其他一些问题声称这是不可能的:获取变量的name属性

我可以理解,不可能获得变量的名称,因为简单的编译器没有该信息,但是我仍然急于查看其他人是否对此问题有任何解决方案。

Eri*_*ori 9

如Kotlin 文档中关于Reflection的陈述:

val x = 1

fun main() {
    println(::x.get())
    println(::x.name) 
}
Run Code Online (Sandbox Code Playgroud)

表达式的::x计算结果为type的属性对象KProperty<Int>,该属性对象使我们可以使用get()属性读取值或使用name属性检索属性名称。

  • 如何用“this”来做到这一点? (2认同)

小智 9

用于memberProperties获取类属性和其他属性的名称。例如:

YourClass::class.memberProperties.map {
 println(it.name)
 println(it.returnType)
}
Run Code Online (Sandbox Code Playgroud)


Har*_*eet 6

我认为委托属性是我问题的解决方案:

class Delegate {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
    return "$thisRef, thank you for delegating '${property.name}' to me!"
}

operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
    println("$value has been assigned to '${property.name}' in $thisRef.")
  }
}
Run Code Online (Sandbox Code Playgroud)

致谢:Roland
来源:https : //kotlinlang.org/docs/reference/delegated-properties.html