![]() |
VOOZH | about |
Kotlin Reflection is a powerful feature that allows a program to inspect and interact with its own structure at runtime. It enables developers to work with classes, properties, functions, constructors, and more all while the program is running.
Reflection is useful in many situations, such as:
Kotlin supports both Java Reflection APIs and its own set of Kotlin Reflection APIs, making it flexible and interoperable with Java.
Kotlin's reflection tools are mainly available in the kotlin.reflect package. This package provides Kotlin-specific reflection features that are more concise and functional than Java’s reflection API.
To use Kotlin reflection, we need to add the following dependency in your build.gradle.kts (Module :app) file:
dependencies {
...
implementation("org.jetbrains.kotlin:kotlin-reflect")
}
To get a reference to a class at runtime, Kotlin provides the class reference operator ::class. This is useful when you need information about the structure of a class. There are two types of Class References
Example:
Output:
This is a class reference: class ReflectionDemo
This is a bounded class reference: class ReflectionDemo
We can obtain a functional reference to every named function that is defined in Kotlin. This can be done by preceding the function name with the :: operator. These functional references can then be used as parameters to other functions.
Example:
Output:
[3, 6, 9]In the case of overloaded functions, we can either explicitly specify the type of the function or it can be implicitly determined from the content.
Example:
Output:
Kotlin Reflection
8
We can obtain property reference in a similar fashion as that of function, using the :: operator. If the property belongs to a class then the class-name should also be specified with the :: operator. These property references allow us to treat a property as an object that is, we can obtain their values using get function or modify it using set function.
Example:
Output:
10
20
For class properties, use the class name or instance:
Output:
5.899 The references to constructors of a class can be obtained in a similar manner as the references for methods and properties. These references can be used as references to a function which returns an object of that type. However, these uses are rare.
Example:
Output:
Alice