如何在Kotlin中获取变量的名称? [英] How to get the name of a variable in Kotlin?

查看:1209
本文介绍了如何在Kotlin中获取变量的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Kotlin class in my application with a lot of attributes, what I want to build is a method that stores the variable name in a dictionary. The dictionary looks like this:

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

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

The purpose of this is to store the changes made to a certain attribute, I store the name of the variable as the key and in the Pair I store the old value and the new value. To notify a change I use the Observer pattern. So whenever a setter is called from an attribute a change will be notified and stored to the dictionary.

以下代码导致以下问题:

The code below results in the folowing:

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

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

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

Right now I am just hardcoding the variable name in as a String, so my question is:

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

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

I saw the same question in Java: Java Reflection: How to get the name of a variable?

关于同一主题的其他一些问题也声称不可能:获取变量的名称属性

Also some other questions about the same topic claiming it is not possible: Get the name property of a variable

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

I can understand that it is not possible to get the name of a variable, because the compiler simple doesn't have that information, but I am still currious to see if others have any sollution for this problem.

推荐答案

我认为代表财产是解决我的问题的方法:

I think delegate propperties are the sollution to my problem:

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

抵免额转到:罗兰 来源: https://kotlinlang.org/docs/reference/delegated-properties.html

Credits go to:Roland Source: https://kotlinlang.org/docs/reference/delegated-properties.html

这篇关于如何在Kotlin中获取变量的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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