카테고리 없음

[Kotlin] instance 순회, 변수를 통해 value접근

IagreeBUT 2023. 10. 26. 11:14
728x90

 

 

data class로 instance객체를 생성한 뒤

property (field) name을 순회하는 방법

for(prop in Class명::class.memberProperties) {
	println("${prop.name} : ${prop.get(해당클래스로만든 instance)");
}

근데 이렇게하면.. 왜인지 field들이 abc순서대로 정렬되어 출력된다

 

Class명::class.primaryConstructor?.parameter?.forEach{
	println("${it.name} : ${it.type}") 
    
    val property:String = it.name.toString()
    println(instance.javaClass.kotlin.memberProperties.first{it.name==property}.get(instance))

}

이렇게 선언하면 내가 선언한 필드명대로 

필드이름 / 타입 / 해당 필드에 해당하는 instance.{fieldName} 이거 값

이렇게 접근 가능하다

 

근데 이렇게까지 해야하나..? 

라이브러리 반입이 reflect까지밖에안되어 있어서 어쩔수 없긴 하지만... 이건좀 

 

https://stackoverflow.com/questions/35525122/kotlin-data-class-how-to-read-the-value-of-property-if-i-dont-know-its-name-at

 

Kotlin data class: how to read the value of property if I don't know its name at compile time?

How can I read the value of property in a Kotlin data class instance if the property name is only known at runtime?

stackoverflow.com

https://stackoverflow.com/questions/35525122/kotlin-data-class-how-to-read-the-value-of-property-if-i-dont-know-its-name-at

 

Kotlin data class: how to read the value of property if I don't know its name at compile time?

How can I read the value of property in a Kotlin data class instance if the property name is only known at runtime?

stackoverflow.com

https://stackoverflow.com/questions/51687098/kotlin-get-property-in-the-same-order-they-are-declared

 

Kotlin get property in the same order they are declared

I have found some articles on getting properties in Kotlin, but not really something on getting properties in their declared order. So for now I have created an annotation and used it to declare ...

stackoverflow.com

 

728x90