Skip to content

Instantly share code, notes, and snippets.

@socar-dorma
Created June 8, 2021 05:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save socar-dorma/161c58fda3b848184c62ae287ca59e4b to your computer and use it in GitHub Desktop.
Save socar-dorma/161c58fda3b848184c62ae287ca59e4b to your computer and use it in GitHub Desktop.
reflection을 이용한 공통코드 조회
object Codes {
// ... other codes ...
enum class SettlementType(val label: String, val value: String) {
AUTO("자동", "STLTP_AUTO"),
MANUAL("수동", "STLTP_MANUAL");
companion object {
fun getByValue(value: String): SettlementType? = values().find { it.value == value }
}
}
// ... other codes ...
}
data class Code(
val id: Int,
val group: String,
val name: String,
val label: String
)
fun Codes.getCodes(groups: List<String>): Any {
val codeNames = groups.map { CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, it) }
val data = mutableMapOf<String, List<Code>>()
this::class.nestedClasses.filter { codeNames.contains(it.simpleName) }
.forEach { codes ->
val groupUpperCamel = codeNames.first { it == codes.simpleName }
val groupUpperUnderscore = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, groupUpperCamel)
val groupLowerCamel = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, groupUpperCamel)
val children = codes.java.getDeclaredMethod("values").invoke(null) as Array<*>
val list = children.mapIndexedNotNull { index, child ->
if (child != null) {
val label = child::class.declaredMemberProperties.find { it.name == "label" }?.getter?.call(child) as String
val value = child::class.declaredMemberProperties.find { it.name == "value" }?.getter?.call(child) as String
Code(index, groupUpperUnderscore, value, label)
} else {
null
}
}
data[groupLowerCamel] = list
}
return data
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment