【问题标题】:How to get the name of a variable in Kotlin?如何在 Kotlin 中获取变量的名称?
【发布时间】:2018-11-07 11:04:18
【问题描述】:

我的应用程序中有一个 Kotlin 类,它有很多属性,我想要构建一个将变量名存储在字典中的方法。字典是这样的:

HashMap<String, Pair<Any, Any>>()

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

下面的代码结果如下:

var person = Person("Harry", 44)
person.age = 45

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

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

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

我在 Java 中看到了同样的问题:Java Reflection: How to get the name of a variable?

还有一些关于同一主题的其他问题声称这是不可能的:Get the name property of a variable

我可以理解无法获取变量的名称,因为简单的编译器没有该信息,但我仍然很想看看其他人是否有任何解决此问题的方法。

【问题讨论】:

  • 你知道delegated properties是什么吗?
  • 不,我不知道委托属性,看起来不错,我会看看,谢谢。

标签: kotlin variable-names delegated-properties


【解决方案1】:

如 Kotlin documentation about Reflection 中所述:

val x = 1

fun main() {
    println(::x.get())
    println(::x.name) 
}

表达式::x 求值为KProperty&lt;Int&gt; 类型的属性对象,这允许我们使用get() 读取其值或使用name 属性检索属性名称。

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 嗯...也许它可以满足您的需求,但请务必查看 observable 和 properties in a map 变体,它们甚至可能更合适或更容易实现。
    【解决方案3】:

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

    YourClass::class.memberProperties.map {
     println(it.name)
     println(it.returnType)
    }
    

    【讨论】:

    • 如何获取该字段的值?
    猜你喜欢
    • 1970-01-01
    • 2019-06-16
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 2017-08-06
    • 2021-08-13
    • 1970-01-01
    相关资源
    最近更新 更多