Kotlin Reflection Getting values of all properties of a class


Example

Given Example class extending BaseExample class with some properties:

open class BaseExample(val baseField: String)

class Example(val field1: String, val field2: Int, baseField: String): 
    BaseExample(baseField) {
    
    val field3: String
        get() = "Property without backing field"

    val field4 by lazy { "Delegated value" }

    private val privateField: String = "Private value"
}

One can get hold of all properties of a class:

val example = Example(field1 = "abc", field2 = 1, baseField = "someText")

example::class.memberProperties.forEach { member ->
    println("${member.name} -> ${member.get(example)}")
}

Running this code will cause an exception to be thrown. Property private val privateField is declared private and calling member.get(example) on it will not succeed. One way to handle this it to filter out private properties. To do that we have to check the visibility modifier of a property's Java getter. In case of private val the getter does not exist so we can assume private access.

The helper function and it's usage might look like this:

fun isFieldAccessible(property: KProperty1<*, *>): Boolean {
    return property.javaGetter?.modifiers?.let { !Modifier.isPrivate(it) } ?: false
}

val example = Example(field1 = "abc", field2 = 1, baseField = "someText")

example::class.memberProperties.filter { isFieldAccessible(it) }.forEach { member ->
    println("${member.name} -> ${member.get(example)}")
}

Another approach is to make private properties accessible using reflection:

example::class.memberProperties.forEach { member ->
    member.isAccessible = true
    println("${member.name} -> ${member.get(example)}")
}