Is it possible to find methods during runtime passing a variable or a string name in Kotlin like in groovy

102 Views Asked by At

For example there is the possibility in groovy to execute a method using following code:

    @Test
    void shouldAccessMethodDynamically() {
       DynamicClass dynamic = new DynamicClass()
       String name = 'dynamicMethod'

       assert dynamic."$name"() == "dynamic"
       assert dynamic."dynamicMethod"() == "dynamic"
    }      

Is this also possible in Kotlin?

1

There are 1 best solutions below

0
On BEST ANSWER

You can call a method by name using regular java reflection API:

val dynamic = DynamicClass()
val name = "dynamicMethod"

dynamic.javaClass.getMethod(name).invoke(dynamic)

If you like to do it in more "kotlin way", you can use it like:

DynamicClass::class.memberFunctions.find { it.name == "name" }?.call(dynamic)