Sobes.tech
Junior — Middle

Kuidas Kotlinis refleksiooniga töötatakse?

sobes.tech AI

Vastus AI-lt

In Kotlin, working with reflection is done through the kotlin.reflect package. The main class is KClass, which represents a class at runtime. Reflection allows you to obtain information about class properties, functions, constructors, and annotations.

Example of getting the class name and list of its properties:

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, DI, or framework development.