lundi 17 août 2020

New instance of data class with reflection

I am creating a new data class instance with reflection. Is there a better solution than the code below?

private inline fun <reified TEntity : Any> queryMapping(params: MultiValueMap<String, String>): TEntity {
    val entity = TEntity::class
    var resultInstance = entity.createInstance()

    params.forEach { param ->

        val property = entity.memberProperties.find { member ->
            member.name.toLowerCase() == param.key.toLowerCase() }

        if (property is KMutableProperty<*>) {
            when(property.returnType.javaType.typeName.toLowerCase()) {
                "int" -> property.setter.call(resultInstance, param.value.first().toInt())
                "java.lang.string" -> property.setter.call(resultInstance, param.value.first())
            }
        }
    }

    return resultInstance
}

In this case data class properties has to be mutable (var). Example data class:

data class PostPerson(
        var Id: Int = 0,
        var Name: String = "",
        var Age: Int = 0)




Aucun commentaire:

Enregistrer un commentaire