Skip to content

Instantly share code, notes, and snippets.

@DavidSanf0rd
Created June 20, 2017 00:39
Show Gist options
  • Save DavidSanf0rd/9725485155bc0c4c681eb038b21c457a to your computer and use it in GitHub Desktop.
Save DavidSanf0rd/9725485155bc0c4c681eb038b21c457a to your computer and use it in GitHub Desktop.
Using kotlin reflection to get the name, type and values of any class properties
import kotlin.reflect.full.declaredMemberProperties
/**
* Created by sanf0rd on 19/06/17.
*/
fun readProperties(instance: Any) {
val clazz = instance.javaClass.kotlin
clazz.declaredMemberProperties.forEach {
println("${it.name} --[${it.returnType}]---> ${it.get(instance)}")
}
}
data class MyData(val name: String, val age: Int)
fun main(args: Array<String>) {
val data = MyData(name = "Sanford", age = 19)
readProperties(data)
}
@maxrks
Copy link

maxrks commented May 3, 2021

it.get(instance) coud be it.getter.call(instance!!) in kotlin later version.

@MarineDr
Copy link

MarineDr commented Apr 9, 2024

it.get(instance) coud be it.getter.call(instance!!) in kotlin later version.

thanks !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment