java反射获取⽗类和⼦类字段值、赋值import org.springframework.util.ReflectionUtils;
import flect.Field;
import java.util.*;
public static void setValueByPropName(String tar, Object o, Object val, Class clazz) {
Field field = getFiled(tar, clazz);
field.setAccessible(true);
ReflectionUtils.setField(field, o, val);
}
public static Field getFiled(String tar, Class clazz) {
java反射的作用及应用场景
String error = null;
Field field = null;
while (clazz != null) {
try {
field = DeclaredField(tar);
error = null;
break;
} catch (Exception e) {
clazz = Superclass();
error = e.getMessage();
}
}
if (error != null || field == null) {
throw new RuntimeException("⽆法获取源字段:" + tar);
}
return field;
}
public static Object getValueByPropName(String filedName, Object o, Class clazz) {
Field field = getFiled(filedName, clazz);
field.setAccessible(true);
Field(field, o);
}
调⽤⽅式:
// 获取id的值
Object var = getValueByPropName("id", a, clazz);
// 赋值name -> lisi
setValueByPropName("name", a, "lisi", clazz);