Skip to content

Instantly share code, notes, and snippets.

@ruwanka
Last active March 25, 2018 03:56
Show Gist options
  • Save ruwanka/523e77b72ddbbdc556135857c7dc65bd to your computer and use it in GitHub Desktop.
Save ruwanka/523e77b72ddbbdc556135857c7dc65bd to your computer and use it in GitHub Desktop.
Kotlin Refleciton API
package com.ruwanka.kotlin.reflections
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.full.functions
import kotlin.reflect.full.memberProperties
fun main(args: Array<String>) {
// get access to KClass
val kClass = Student::class
// prints fully qualified name
println(kClass)
// prints all properties + member functions
kClass.members.forEach { println(it) }
// prints only properties
kClass.memberProperties.forEach { println(it) }
// prints only member functions
kClass.functions.forEach { println(it) }
// prints all constructors
kClass.constructors.forEach { println(it) }
// prints all declared member properties
kClass.declaredMemberProperties.forEach { println(it) }
// create new instance
val studentConstructor = ::Student
var highSchoolStudent = studentConstructor.call("Archie", 17, "Riverdale High")
println(highSchoolStudent)
// create new instance using callBy with parameter map
val nameParam = studentConstructor.parameters.first { it.name == "name" }
val ageParam = studentConstructor.parameters.first { it.name == "age" }
val schoolParam = studentConstructor.parameters.first { it.name == "school" }
highSchoolStudent = studentConstructor.callBy(mapOf(nameParam to "Betty",
ageParam to 16,
schoolParam to "RiverDale High"))
println(highSchoolStudent)
// create new instance using callBy with positions
highSchoolStudent = studentConstructor.callBy(mapOf(studentConstructor.parameters[0] to "Veronica",
studentConstructor.parameters[1] to 16,
studentConstructor.parameters[2] to "RiverDale High"))
println(highSchoolStudent)
// accessing properties of runtime object
val schoolProperty = Student::class.declaredMemberProperties.find { it.name == "school" }
println(schoolProperty?.get(highSchoolStudent))
// invoking functions
val getRankFunc = highSchoolStudent::getRank
getRankFunc.invoke()
getRankFunc.call()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment