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>
then:
val member = Test::class.members.find { it.name=="TEST" }
println(member)
println(member.call(Test())
output:
val generic.Test.TEST: kotlin.String
Hello
member type is Kcallable<*>?
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/-k-callable/index.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With