jeudi 11 novembre 2021

Kotlin: get members of a data class by reflection in the order they have been defined

Assume the following simple example data class:

data class SomeDataClass(
  var id: String,
  var name: String,
  var deleted: String
)

With the following code it is possible to get the properties (and set or get their values):

import kotlin.reflect.full.memberProperties

val properties = SomeDataClass::class.memberProperties

print(properties.map { it.name })   // prints:   [deleted, id, name]

The map within the print statement will return a List with the name of the properties in alphabetical order. I need the list in the order they have been defined in the source code, in this case: [id, name, deleted].

It doesn't seem achievable purely through reflection. The only solution I could come up with is to use a helper class defining the order:

val SomeDataClass_Order = listOf("id", "name", "deleted")

This wouldn't be a problem for one or two classes, but it is for hundreds of data classes with the largest one having up to almost one hundred properties.

Any idea would be welcome. I do not need detailed code, rather hints (like parsing the source code, annotations, etc).





Aucun commentaire:

Enregistrer un commentaire