All Downloads are FREE. Search and download functionalities are using the official Maven repository.

run.smt.ktest.util.tomap.to-map.kt Maven / Gradle / Ivy

There is a newer version: 1.0.0
Show newest version
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




© 2015 - 2024 Weber Informatics LLC | Privacy Policy