在Kotlin中按名称动态获取函数 [英] Get function by name dynamically in Kotlin

查看:668
本文介绍了在Kotlin中按名称动态获取函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Kotlin中按名称动态获取函数?

How can I dynamically get a function by name in Kotlin ?

即:

fun myFunc11() { println("Very useful function 11") }

val funcName = "myFunc" + 11
val funcRef = getFunction(funcName)

funcRef()


可接受的答案似乎是正确的,但是该代码当前在Kotlin中遇到了一些错误.提交的错误报告: https://youtrack.jetbrains.com/issue/KT-10690


The accepted answer appears to be correct, however the code is currently hitting some bug in Kotlin. Bug report submitted: https://youtrack.jetbrains.com/issue/KT-10690

推荐答案

在名为Global.kt的文件中定义的全局函数(例如fun myFunc11() { ... })将被编译为名为GlobalKt的类上的static方法,如文档.

The global functions such as fun myFunc11() { ... } defined in file named i.e. Global.kt are compiled to static methods on a class named GlobalKt as described in the documentation.

要按名称获取函数引用,您需要加载定义它的类.如果您知道定义函数引用的文件名,则可以执行以下操作:

To get a function reference by name you'll need to load the class that defines it. If you know the file name that defines the function reference you're trying to find you 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
}

然后您可以找到并调用Global.kt文件中定义的函数:

Then you can find and call function defined in Global.kt file:

fun myFunc11() { println("Very useful function 11") }

像这样:

val kFunction = getFunctionFromFile("Global", "myFunc11")
kFunction?.call()

但是,以上内容毫无用处.更好的解决方案是搜索类路径中所有可用的后缀为Kt的所有类,以访问所有 global 函数.但是,由于jvm类加载器的性质,如此答案中所述,这会涉及更多内容.

However the above is pretty useless. A better solution would be to search through all classes available in classpath and suffixed with Kt to reach all global functions. However due to nature of jvm class loaders this is a bit more involved as described in this answer.

这篇关于在Kotlin中按名称动态获取函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆