com.neko233.config233.utils.BeanUtilsForConfig233.kt Maven / Gradle / Ivy
package com.neko233.config233.utils
import java.lang.reflect.Modifier
object BeanUtilsForConfig233 {
@JvmStatic
fun mapToBeanAny(
map: Map,
clazz: Class
): T {
val instance = clazz.getDeclaredConstructor().newInstance()
var logValue: Any? = null
clazz.declaredFields.forEach { field ->
try {
if (Modifier.isStatic(field.modifiers)) {
return@forEach
}
val value = map[field.name]
?: return@forEach
logValue = value
// 是否同一个类型
if (field.type.isPrimitive) {
field.isAccessible = true
field.set(instance, value)
return@forEach
}
if (field.type.isAssignableFrom(value.javaClass)) {
field.isAccessible = true
field.set(instance, value)
return@forEach
}
if (field.type.isAssignableFrom(value::class.javaObjectType)) {
field.isAccessible = true
field.set(instance, value)
return@forEach
}
} catch (e: Exception) {
System.err.println("[${BeanUtilsForConfig233::class.java.name}] 反射字段set 报错. field=${field.name}, value=${logValue}")
e.printStackTrace()
}
}
return instance
}
}