Kotlin中Class#getDeclaredField
的等效代码是什么?我正在寻找一个纯粹的Kotlin实现...也许是一种反思?
class Test {
public static final String TEST = "Hello";
public static void main(String[] args) {
System.out.println(
Test.class.getDeclaredField("TEST").get(Test.class));
}
}
答案 0 :(得分:2)
首先,添加此依赖项以避免运行时错误
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
<version>1.3.50</version>
</dependency>
然后:
val member = Test::class.members.find { it.name=="TEST" }
println(member)
println(member.call(Test())
输出:
val generic.Test.TEST: kotlin.String
Hello
成员类型为可通话<*>?
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/-k-callable/index.html