In this blog, we going to discuss Reflection in Kotlin.
Inside of program file some time we want to utilize some classes and its member like constructor, functions and variables runtime. We can use Reflection in Kotlin for utilizing the functionality at runtime.
Reflection is a set of languages and library feature that help us to introspect structure of our program at runtime.
Reflection provides the API feature of java reflection and its own set of functionality.
Implementation
Class references
We can get the reference of the class at runtime if the class is statically known. For the class reference we use the class reference operator.
Obtaining the reference of a class from its instance is known as bounded class reference.
1 2 3 4 5 6 7 8 9 10 11 |
class ReflectionClass { } fun main() { val classReference = ReflectionClass::class println("Class Reference $classReference") val boundedClassReference = ReflectionClass() println("Bounded Class Reference ${boundedClassReference::class}") } |
Function References
We can get the reference of the function by preceding the function name with :: operator.
We can get the reference of the named function on kotlin and pass these reference as parameter to the another functions.
1 2 3 4 5 6 7 8 9 10 |
fun reflectionFunction(name: String){ println("Name: $name") } fun main(){ val refFunction = ::reflectionFunction println(refFunction) } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fun reflectionFunction(name: String): String{ return "Name: $name" } fun reflectionFunction(name: String, age: String): String { return "Name: $name Age: $age" } fun main(){ // Specifying the type explicitly for the overloaded function val refFunctionEx: (String,String) -> String = ::reflectionFunction println(refFunctionEx) // getting reference implicitly for the overloaded function val refFunctionIm = reflectionFunction("Jack","25") println(refFunctionIm) } |
Constructor Reference
If is same as the function reference and property reference. On the constructor reference we reference simply by preceding the class name with :: operator like below:
1 2 3 4 5 6 7 |
class ReflectionClass(name: String) { } fun main(){ val refConstructor = ::ReflectionClass println(refConstructor.name) } |
Conclusion:
In this blog, we have learned Reflection in Kotlin and its uses.
For more information regarding the Sealed classes in Kotlin follow link.
Thanks for reading this blog. You can also check other blogs from here.