Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin get declared member property value

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));
    }
}
like image 702
Küroro Avatar asked Oct 17 '25 05:10

Küroro


1 Answers

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

like image 98
Naor Tedgi Avatar answered Oct 20 '25 10:10

Naor Tedgi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!