在Kotlin中获取静态成员属性的名称

时间:2020-04-23 14:07:36

标签: kotlin reflection

在Kotlin项目中,我有一个类似的javaclass:

public final class BuildConfig {
  public static final String FOO = "HelloWorld";
  public static final String ALT_FOO = "HelloWorldAlt";
}

如何获取值为FOO的字符串? (不是字段的值,而是字段的名称)

val theName = "FOO"

例如,稍后我将有一张地图。

val map = mapOf("FOO" to "HelloWorldAlt", "BAR" to "CoronaGotMeInside")

我想做以下事情:

val result = map[theName]
println(result)
// HelloWorldAlt

我知道我可以像下面那样获得所有字段值,但是我无法弄清楚如何从单个静态变量中获取静态成员变量名称。我不想迭代所有staticProperties。我想明确地查找一个。

val notResult = BuildConfig::class.staticProperties.filter { it.name == "FOO" }[0].getter.call()
println(notResult)
// HelloWorld

作为一个非迭代解决方案的示例,我想要这样的东西:

val theName = BuildConfig.FOO::variableName() // Totally made up, but I want to act on the singular constant, not on a collection 

这将使我在使用变量命名映射键时具有一定的编译时置信度。我知道疯了。

1 个答案:

答案 0 :(得分:0)

感谢Tenfour04

BuildConfig::FOO.name

::是元编程的一部分:https://towardsdatascience.com/kotlin-the-next-frontier-in-modern-meta-programming-8c0ac2babfaa

.name结合的是反射:

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

https://kotlinlang.org/docs/reference/reflection.html

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/-k-mutable-property/

Why getting class in Kotlin using double-colon (::)?

相关问题