通用工具类:
package com.zlp.util;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.lang.reflect.Field;
public class ReflectUtil {
/**
* 反射获取对象的属性值
*
* @param object 对象(要遍历的对象)
* @param targetFieldName 属性名
* @return 属性值
*/
public static Object getFieldValueByObject(Object object, String targetFieldName) {
Object result = null;
Class objClass = object.getClass();
Field[] fields = objClass.getDeclaredFields();
for (Field field : fields) {
String currentFieldName = "";
try {
boolean hasJsonProperty = field.isAnnotationPresent(JsonProperty.class);
if (hasJsonProperty) {
currentFieldName = field.getAnnotation(JsonProperty.class).value();
} else {
currentFieldName = field.getName();
}
if (currentFieldName.toUpperCase().equals(targetFieldName.toUpperCase())) {
//设置属性的可访问性
field.setAccessible(true);
result = field.get(object);
return result;
}
} catch (Exception e) {
// 异常
System.out.println("获取对象的属性值异常:{}" + e.getMessage());
}
}
return result;
}
/**
* 反射设置对象的属性值
*
* @param object
* @param targetFieldName
* @param value
*/
public static void setFieldValueByObject(Object object, String targetFieldName, Object value) {
if (null == object) {
return;
}
try {
Class<?> objectClass = object.getClass();
// 获取属性
Field declaredField = objectClass.getDeclaredField(targetFieldName);
// 设置当前属性可访问
declaredField.setAccessible(true);
// 设置属性值
declaredField.set(object, value);
} catch (Exception e) {
System.out.println("设置对象的属性值异常:{}" + e.getMessage());
}
}
}
测试:
package com.zlp.test;
import com.zlp.util.ReflectUtil;
public class TestController {
public static void main(String[] args) {
User user = new User("1个凡夫俗子", 18);
// 根据属性名称获取对应的值
Object name = ReflectUtil.getFieldValueByObject(user, "name");
System.out.println("通过反射获取name字段值:" + name.toString());
// 根据属性名称设置值
ReflectUtil.setFieldValueByObject(user, "age", 28);
System.out.println("通过反射设置age字段值:" + user.getAge());
}
}