Home > front end >  Why class member property reflection in Kotlin?
Why class member property reflection in Kotlin?

Time:05-31

In 'Kotlin in Action', it says "if a memberProperty refers to the age property of the Person class, memberProperty.get(person) is a way to dynamically get the value of person.age" with code(10.2.1 The Kotlin Reflection API):

class Peron(val name: String, val age: Int)
>> val person = Person("Alice", 29)
>> val memberProperty = Person::age
>> println(memberProperty.get(person))
29

I can't understand why this example refers to "dynamically" getting the value of property. It just works when I run this code:

println(person.age)

Is there any other case or example of member property reflection?

CodePudding user response:

For example, say you want to write a function which prints all the properties of an object along with their values, this is how you can do that:

inline fun <reified T: Any> T.printProperties() {
    T::class.memberProperties.forEach { property ->
        println("${property.name} = ${property.get(this)}") // You can't use `this.property` here
    }
}

Usage:

data class Person(val firstName: String, val lastName: String)
data class Student(val graduate: Boolean, val rollNumber: Int)

fun main() {
    val person = Person("Johnny", "Depp")
    val student = Student(false, 12345)
    person.printProperties()
    student.printProperties()
}

Output:

firstName = Johnny
lastName = Depp
graduate = false
rollNumber = 12345
  • Related