https://kotlinlang.org logo
#reflect
Title
# reflect
s

Serge

11/08/2018, 10:08 PM
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

udalov

11/09/2018, 1:43 PM
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

Serge

11/09/2018, 4:37 PM
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
5 Views