Skip to content

Instantly share code, notes, and snippets.

@virtualsafety
Forked from DavidSanf0rd/KotlinReflection.kt
Created September 17, 2019 14:48
Show Gist options
  • Save virtualsafety/669dc081a6f4ff5c99fd150e8d6fcf47 to your computer and use it in GitHub Desktop.
Save virtualsafety/669dc081a6f4ff5c99fd150e8d6fcf47 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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment