[英]Is there a way to get Kotlin function's owner via reflection
Suppose we have the following functions:假设我们有以下函数:
class MyClass {
fun myFunction() {}
companion object {
fun myStaticFunction() {}
}
}
fun myTopLevelFunction() {}
When I am debugging thru the following:当我通过以下方式进行调试时:
val functions = listOf(
MyClass::myFunction,
MyClass.Companion::myStaticFunction,
::myTopLevelFunction
)
functions.forEach {
val names = (it::class.java).fields.map {
method -> println(method.name)
}
Intellij can correctly show me in "Evaluate Expression" this information Intellij 可以在“评估表达式”中正确显示此信息
But I cannot find a way to do it via reflection.但我找不到通过反射来做到这一点的方法。 For instance, I cannot figure out how to read function's owner.例如,我无法弄清楚如何读取函数的所有者。 What am I missing?我错过了什么? TIA. TIA。
In Intellij I can see functions' owners like this在 Intellij 中,我可以看到这样的函数所有者
myFunction -> MyClass
myStaticFunction -> MyClass.Companion
myTopLevelFunction -> MyFileNameKt
I believe KFunction
does not provide us with such capability.我相信KFunction
没有为我们提供这样的能力。 If you are not afraid of using publicly available utils from kotlin.jvm.internal
package then you can check if KFunction
is a CallableReference
and then use its owner
property:如果您不害怕使用kotlin.jvm.internal
CallableReference
中的公开可用的实用程序,那么您可以检查KFunction
是否为owner
属性:
functions.forEach {
if (it is CallableReference) {
println(it.owner)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.