Sobes.tech
Junior — Middle

How is reflection handled in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, reflection is handled using the kotlin.reflect package. The main class is KClass, which represents a class at runtime. Reflection can be used to obtain information about properties, functions, constructors, and annotations of classes.

Example of getting the class name and its properties list:

import kotlin.reflect.full.memberProperties

class User(val name: String, val age: Int)

fun main() {
    val kClass = User::class
    println("Class name: ${kClass.simpleName}")
    for (prop in kClass.memberProperties) {
        println("Property: ${prop.name}")
    }
}

You can also invoke functions and create instances via reflection, but sometimes it requires using the Java Reflection API (java.lang.reflect).

Reflection is useful for dynamic analysis and working with objects, for example, in serialization, dependency injection, or framework development.

How is reflection handled in Kotlin? — Android - sobes.tech