Reflection Kotlin按声明的顺序获取属性
我找到了一些关于在Kotlin中获取属性的文章,但实际上没有找到关于按照声明的顺序获取属性的文章 所以现在我已经创建了一个注释,并用它来声明属性的顺序Reflection Kotlin按声明的顺序获取属性,reflection,kotlin,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",
@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(':')
}
是否有更好的方法按声明的顺序获取属性?更简单的方法是从构造函数读取属性:
ClassWithSortedProperties::class.
primaryConstructor?.
parameters?.
forEachIndexed { i, property ->
println("$i $property")
}
数据类为数据生成方法 如果您确切知道有多少个字段,则无需进行反思即可完成,但这需要详细的“样板”代码:
val item = ClassWithSortedProperties("Z", "X", "C")
val (v1, v2, v3) = item // destructure (assign to multiple variables)
val listOfProperties = listOf(v1, v2, v3) // list of all fields
// you can also get a single item at given position:
val secondProperty = item.component2()