run.smt.ktest.util.tomap.to-map.kt Maven / Gradle / Ivy
package run.smt.ktest.util.tomap
import java.lang.reflect.Field
/**
* Convert any POJO to map
*/
fun T.toMap(): Map {
val classType: Class<*> = this.javaClass
return collectFields(classType)
.associate {
it.name to it.extractFrom(this)
}
}
fun T.toMap(deep: Boolean): Map {
if (!deep) {
return toMap()
}
return toMap().mapValues {
if (it.value == null || it.value is Number || it.value is Iterable<*> || it.value is Iterator<*> || it.value is Map<*, *> || it.value is String) {
it.value
} else {
it.value!!.toMap(deep = true)
}
}
}
private fun Field.extractFrom(obj: T): Any? {
isAccessible = true
return get(obj)
}
private fun collectFields(clazz: Class): Array =
if (clazz != Any::class.java) {
collectFields(clazz.superclass)
} else {
emptyArray()
} + clazz.declaredFields