import org.springframework.util.ReflectionUtils; import java.lang.reflect.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) { String error = null; Field field = null; while (clazz != null) { try { field = clazz.getDeclaredField(tar); error = null; break; } catch (Exception e) { clazz = clazz.getSuperclass(); 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); return ReflectionUtils.getField(field, o); }
调用方式:
// 获取id的值
Object var = getValueByPropName("id", a, clazz);
// 赋值name -> lisi
setValueByPropName("name", a, "lisi", clazz);