【问题标题】:Getting the name of a static member property in Kotlin在 Kotlin 中获取静态成员属性的名称
【发布时间】:2020-04-23 14:07:36
【问题描述】:

在 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

我知道我可以获取如下所示的所有字段值,但我不知道如何从单个静态 var 中获取静态成员变量名称。我不想迭代所有的静态属性。我想明确地查找一个。

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 

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

【问题讨论】:

  • BuildConfig::FOO.name
  • 哈!难以置信,这么多谷歌搜索,我找不到。谢谢把它作为答案(如果你有文档链接),我会标记为已回答! (我在尝试::BuildConfig.FOO.nameduh!)

标签: kotlin reflection


【解决方案1】:

感谢 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 (::)?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    相关资源
    最近更新 更多