Middle
How to use reflection in Kotlin?
sobes.tech AI
Answer from AI
Reflection in Kotlin allows obtaining information about classes, functions, properties, and constructors at runtime and working with them dynamically.
The main classes for reflection are in the kotlin.reflect package:
KClass: Represents a class.KFunction: Represents a function.KProperty: Represents a property.KParameter: Represents a parameter.
Getting KClass:
- For a static class:
MyClass::class - For an instance of an object:
obj::class - By class name as a string:
Class.forName("com.example.MyClass").kotlin
Examples of usage:
Getting information about a class:
// Getting KClass
val kClass = String::class
// Getting class name
val className = kClass.simpleName // String
// Getting list of constructors
val constructors = kClass.constructors
// Getting list of class members (functions, properties, nested classes)
val members = kClass.members
Calling a function by its name:
class Greeter {
fun sayHello(name: String) {
println("Hello, $name!")
}
}
fun main() {
val greeter = Greeter()
val kClass = greeter::class
val sayHelloFunction = kClass.members.first { it.name == "sayHello" } as KFunction<*>
// Calling the function
sayHelloFunction.call(greeter, "World") // Output: Hello, World!
}
Accessing a property by its name:
class Person(var name: String, val age: Int)
fun main() {
val person = Person("Alice", 30)
val kClass = person::class
val nameProperty = kClass.members.first { it.name == "name" } as KMutableProperty1<Person, String>
// Getting the value of the property
val currentName = nameProperty.get(person) // Alice
println(currentName)
// Setting the value of the property (for var)
nameProperty.set(person, "Bob")
println(person.name) // Bob
}
Reflection can be useful for:
- Serialization/deserialization of data.
- Creating frameworks and libraries.
- Testing.
- Dynamic access to properties and methods.
It should be remembered that using reflection can reduce performance due to overhead for dynamic lookup and invocation of members. It can also complicate the code and make it less readable.