Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 300
Jire Avatar asked Nov 25 '15 01:11

Jire


People also ask

What is Kotlin reflect used for?

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.

How does reflection work Kotlin?

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.

Which method gets Package info using reflection?

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.

How do I reference a Class in Kotlin?

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.


1 Answers

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)
    ...
}
like image 129
Alexander Udalov Avatar answered Nov 15 '22 05:11

Alexander Udalov