Kotlin获得声明的成员财产价值 [英] Kotlin get declared member property value
本文介绍了Kotlin获得声明的成员财产价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Class#getDeclaredField
在科特林吗?我正在寻找一个纯粹的Kotlin实现...也许是一种反思?
What is the equivalent code of Class#getDeclaredField
in Kotlin? I'm looking for a pure Kotlin implementation... a reflection perhaps?
class Test {
public static final String TEST = "Hello";
public static void main(String[] args) {
System.out.println(
Test.class.getDeclaredField("TEST").get(Test.class));
}
}
推荐答案
首先,添加此依赖项以避免运行时错误
first, add this dependency to avoid runtime error
<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
这篇关于Kotlin获得声明的成员财产价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文