像这样:
val person = Person(
name = "老中医",
age = 15
)
val map = person.toFields()
map.forEach { (k, v) -> println("Key:$k,value:$v")}
代码
@Target(AnnotationTarget.FIELD)
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
annotation class AutoEnumValue(val value: String)
@Target(AnnotationTarget.FIELD)
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
annotation class AutoField(val value: String = "")
class Person(@AutoField("name")var name:String, @AutoField("age")var age:Int)
inline fun <reified T> T.toFields(): HashMap<String,String>{
val handlerType: Class<T> = T::class.java
val CLAZZ = handlerType.superclass
val fields = handlerType.declaredFields
val superfields = CLAZZ.declaredFields
if (fields.isNotEmpty()) {
Field.setAccessible(fields, true)
Field.setAccessible(superfields, true)
val parts = HashMap<String,String>()
for (field in fields) {
try {
val autoField = field.getAnnotation(AutoField::class.java)
if (autoField != null) {
val value = field.get(this) ?: continue
val key = if (autoField.value.isNotEmpty()) autoField.value else field.name
if (value is Enum<*>) {
//如果对象是枚举
val declaredFields = value.javaClass.declaredFields
Field.setAccessible(declaredFields, true)
for (enumField in declaredFields) {
val annotation = enumField.getAnnotation(AutoEnumValue::class.java)
if (annotation != null) {
val enumValue = enumField.get(value)
if (enumValue != null) {
parts[key] = enumValue.toString()
break
}
}
}
} else {
parts[key] = value.toString()
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
for (field in superfields) {
try {
val autoField = field.getAnnotation(AutoField::class.java)
if (autoField != null) {
val value = field.get(this) ?: continue
val key = if (autoField.value.isNotEmpty()) autoField.value else field.name
if (value is Enum<*>) {
//如果对象是枚举
val declaredFields = value.javaClass.declaredFields
Field.setAccessible(declaredFields, true)
for (enumField in declaredFields) {
val annotation = enumField.getAnnotation(AutoEnumValue::class.java)
if (annotation != null) {
val enumValue = enumField.get(value)
if (enumValue != null) {
parts[key] = enumValue.toString()
break
}
}
}
} else {
parts[key] = value.toString()
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
return parts
}
return HashMap()
}
输出:
Key:name,value:老中医
Key:age,value:15
网友评论