😎

Kotlin Reflection

2020/09/29に公開

Reflection

Reflection is a set of language and library features that allows for introspecting the structure of your own program at runtime

Reflection is distributed as a seperate artifact

On the JVM platform, the runtime component required for using the reflection features is distributed as a separate artifact kotlin-reflect.jar in the Kotlin compiler distribution. This is done to reduce the required size of the runtime library for applications that do not use reflection features.

How to use reflection in Gradle

Add the dependency on kotlin-reflect

dependencies {
  implementation("org.jetbrains.kotlin:kotlin-reflect:1.4.10")
}

Class references reflection

The most basic reflection feature is getting thre runtime reference to a kotlin class

val c = MyClass::class

The reference is a value of type KClass.

  • Kotlin class referrence is different from a java class reference.
  • To obtain a java class reference use th .java property on a KClass
val c = MyClass::class.java

Reflection

Discussion