How can I use reflection on package-level functions, members, etc.? Trying to access javaClass
or class
doesn't work, neither does package
.
Reflection is a set of language and library features that provides the feature of introspecting a given program at runtime. Kotlin reflection is used to utilize class and its members like properties, functions, constructors, etc. at runtime.
The Kotlin Reflection API allows access to a Class reference. This can then be used to introspect the full details of the Kotlin class. This gives access to the Java Class reference – the java.
Package Information. By using Java reflection, we are also able to get information about the package of any class or object. This data is bundled inside the Package class, which is returned by a call to getPackage method on the class object.
To obtain the reference to a statically known Kotlin class, you can use the class literal syntax: val c = MyClass::class //The reference is a value of type KClass. Note that a Kotlin class reference is not the same as a Java class reference.
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
instancekotlinProperty
returns a kotlin.reflect.KProperty
instance by a java.lang.reflect.Field
instanceTo 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)
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With