How to convert a Kotlin data class object to map?

2019-03-20 13:36发布

问题:

Is there any easy way or any standard library method to convert a Kotlin data class object to a map/dictionary of it's properties by property names? Can reflection be avoided?

回答1:

I have the same use case today for testing and ended up i have used Jackson object mapper to convert Kotlin data class into Map. The runtime performance is not a big concern in my case. I haven't checked in details but I believe it's using reflection under the hood but it's out of concern as happened behind the scene.

For Example,

val dataclass = DataClass(p1 = 1, p2 = 2)
val dataclassAsMap = objectMapper.convertValue(dataclass, object: 
TypeReference<Map<String, Any>>() {})

//expect dataclassAsMap == mapOf("p1" to 1, "p2" to 2)


回答2:

The closest you can get is with delegated properties stored in a map.

Example (from link):

class User(val map: Map<String, Any?>) {
    val name: String by map
    val age: Int     by map
}

Using this with data classes may not work very well, however.