reflection - Get function by name dynamically in Kotlin -


how can dynamically function name in kotlin ?

i.e:

fun myfunc11() { println("very useful function 11") }  val funcname = "myfunc" + 11 val funcref = getfunction(funcname)  funcref() 

edit: accepted answer appears correct, code hitting bug in kotlin. bug report submitted: https://youtrack.jetbrains.com/issue/kt-10690

the global functions such fun myfunc11() { ... } defined in file named i.e. global.kt compiled static methods on class named globalkt described in the documentation.

to function reference name you'll need load class defines it. if know file name defines function reference you're trying find can do:

fun getfunctionfromfile(filename: string, funcname: string): kfunction<*>? {     val selfref = ::getfunctionfromfile     val currentclass = selfref.javamethod!!.declaringclass     val classdefiningfunctions = currentclass.classloader.loadclass("${filename}kt")     val javamethod  = classdefiningfunctions.methods.find { it.name == funcname && modifier.isstatic(it.modifiers)}     return javamethod?.kotlinfunction } 

then can find , call function defined in global.kt file:

fun myfunc11() { println("very useful function 11") } 

like so:

val kfunction = getfunctionfromfile("global", "myfunc11") kfunction?.call() 

however above pretty useless. better solution search through classes available in classpath , suffixed kt reach global functions. due nature of jvm class loaders bit more involved described in this answer.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -