vendredi 7 janvier 2022

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

  • 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




Aucun commentaire:

Enregistrer un commentaire