Hi, If I have a package (*.kt file) and have only ...
# reflect
s
Hi, If I have a package (*.kt file) and have only functions declared in it (not any class besides package itself) - is it possible by using reflection to obtain the list of those declared functions? I have tried to do something like this -
Copy code
val o = object{}
val mm = o.javaClass.declaredMethods
and
Copy code
val mm = o::class
  val ff = mm.declaredMemberFunctions
but it doesn't return anything. is it possible at all? if so, would the function modifier affect this search (private, public, etc)?
u
Unfortunately this is not yet natively supported by Kotlin reflection: https://youtrack.jetbrains.com/issue/KT-16479 At the moment, you can use Java reflection and use `.kotlinFunction`/`.kotlinProperty` to map Java reflection objects to Kotlin:
Copy code
// FILE: test.kt

import kotlin.reflect.jvm.*

fun foo() = "OK"

fun main() {
    val functions = (object {}).javaClass.enclosingClass.declaredMethods
    val foo = functions.single { it.name == "foo" }.kotlinFunction!!
    println(foo.call()) // OK
}
s
Thank you, @udalov. I have managed to use java reflection before your post here like this (from within main()) -
Copy code
::main.javaMethod!!.declaringClass.declaredMethods.filter { it.name.startsWith("foo") }.map {it-> it.name}
👍 1