0

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

  • owner (MyClass, MyClass.Companion etc.
  • whether this is a top level function

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.

In Intellij I can see functions' owners like this

myFunction -> MyClass
myStaticFunction -> MyClass.Companion
myTopLevelFunction -> MyFileNameKt
user14381362
  • 165
  • 1
  • 7

1 Answers1

2

I believe KFunction does not provide us with such capability. 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:

functions.forEach {
    if (it is CallableReference) {
        println(it.owner)
    }
}
broot
  • 21,588
  • 3
  • 30
  • 35