Kotlin 按照声明的顺序获取属性

Joh*_*eer 2 reflection kotlin

我找到了一些关于在 Kotlin 中获取属性的文章,但并不是关于按声明的顺序获取属性的内容。

所以现在我已经创建了一个注释并用它来声明属性的顺序

@Target(AnnotationTarget.PROPERTY)
annotation class Pos(val value: Int)

data class ClassWithSortedProperties(
    @Pos(1) val b: String,
    @Pos(2) val a: String = "D",
    @Pos(3) val c: String) {

    class PropertyWithPosition(val pos: Int, val value: String)

    fun toEdifact() = this.javaClass.kotlin.declaredMemberProperties
        .map {
            // Get the position value from the annotation
            val pos = (it.annotations.find { it is Pos } as Pos).value
            // Get the property value
            val value = it.get(this)
            PropertyWithPosition(pos, value.toString())
        }
        .sortedBy { it.pos }
        .joinToString(separator = ":") { it.value }
        .trim(':')
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来按声明的顺序获取属性?

Ale*_*hin 9

更简单的方法是从构造函数中读取属性:

 ClassWithSortedProperties::class.
         primaryConstructor?.
         parameters?.
         forEachIndexed { i, property ->
      println("$i $property")
 }
Run Code Online (Sandbox Code Playgroud)