You can do this through reflection , and this is the same for data classes and regular classes.
The first option is to just use Java reflection:
val name = obj.javaClass .getMethod("getName")
You can even make an extension function:
inline fun <reified T : Any> Any.getThroughReflection(propertyName: String): T? { val getterName = "get" + propertyName.capitalize() return try { javaClass.getMethod(getterName).invoke(this) as? T } catch (e: NoSuchMethodException) { null } }
He calls a public getter. To get the value of a private property, you can change this code with getDeclaredMethod and setAccessible . This will also work for Java objects with corresponding getters (but it skips convention is and has getters for boolean ).
And use:
data class Person(val name: String, val employed: Boolean) val p = Person("Jane", true) val name = p.getThroughReflection<String>("name") val employed = p.getThroughReflection<Boolean>("employed") println("$name - $employed") // Jane - true
The second option includes the use of the
kotlin-reflect library, which you must add to your project separately,
here is its documentation . This will allow you to get the actual value of the Kotlin property, ignoring Java-getters.
You can use javaClass.kotlin to get the current token of the Kotlin class, and then you get the property from it:
val name = p.javaClass.kotlin.memberProperties.first { it.name == "name" }.get(p)
This solution will only work for Kotlin classes, not Java, but much more reliable if you need to work with Kotlin classes: it does not depend on the underlying implementation.