Jire
Jire

Reputation: 10290

Kotlin: How can I use reflection on packages?

How can I use reflection on package-level functions, members, etc.? Trying to access javaClass or class doesn't work, neither does package.

Upvotes: 6

Views: 2613

Answers (1)

Alexander Udalov
Alexander Udalov

Reputation: 32816

Reflection on top level functions or properties is not yet supported in Kotlin but is planned for the future. The only features that are supported at the moment allow you to obtain Kotlin reflection objects corresponding to the given Java reflection objects, requiring you to use Java reflection beforehand:

  • kotlinFunction returns a kotlin.reflect.KFunction instance by a java.lang.reflect.Method instance or by a java.lang.reflect.Constructor instance
  • kotlinProperty returns a kotlin.reflect.KProperty instance by a java.lang.reflect.Field instance

To use them, you must first obtain the corresponding method or field with the Java reflection:

package a

import kotlin.reflect.jvm.*

fun foo() {}

fun reflectFoo() {
    // a.TestKt is the JVM class name for the file test.kt in the package a
    val c = Class.forName("a.TestKt")

    val m = c.getDeclaredMethod("foo")

    val f = m.kotlinFunction!!

    // f is a KFunction instance, so you can now inspect its parameters, annotations, etc.
    println(f.name)
    println(f.returnType)
    ...
}

Upvotes: 10

Related Questions