利用反射,比较两个对象的属性值,以及动态的为属性赋值

mac2025-11-03  17

 1:比较两个对象的属性值,返回不同的属性+值

/** * 比较旧对象与新对象的所有属性值 * @param oldObj * @param newObj * @return 返回 <k,V>-><属性,新值> * @throws IntrospectionException * @throws InvocationTargetException * @throws IllegalAccessException */ public static Map<String, String> contrastObj(Object oldObj, Object newObj) throws IntrospectionException, InvocationTargetException, IllegalAccessException { Class<?> clazz = oldObj.getClass(); Field[] declaredFields = clazz.getDeclaredFields(); HashMap<String, String> map = new HashMap<>(); for (Field field : declaredFields) { System.out.println(field); System.out.println("field:"+field.getName()); PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz); Method getMethod = pd.getReadMethod(); Object o1 = getMethod.invoke(oldObj); Object o2 = getMethod.invoke(newObj); String oldStr = o1 == null ? "" : o1.toString();//避免空指针异常 String newStr = o2 == null ? "" : o2.toString(); if (!oldStr.equals(newStr)){ map.put(field.getName(),newStr); //《属性,新值》\ } } return map; }

2:动态为对象属性赋值

/** * @msg: 通过反射来动态调用get 和 set 方法 / public class ReflectHelper { private Class cls; /** * 传过来的对象 */ private Object obj; private HashMap<String, Method> getMethods = null; private HashMap<String, Method> setMethods = null; public ReflectHelper(Object o) { obj = o; initMethods(); } public void initMethods() { getMethods = new HashMap<>(); setMethods = new HashMap<>(); cls = obj.getClass(); Method[] methods = cls.getMethods(); // 定义正则表达式,从方法中过滤出getter / setter 函数. String gs = "get(\\w+)"; Pattern getM = Pattern.compile(gs); String ss = "set(\\w+)"; Pattern setM = Pattern.compile(ss); // 把方法中的"set" 或者 "get" 去掉,$1匹配第一个 String rapl = "$1"; String param; for (int i = 0; i < methods.length; ++i) { Method m = methods[i]; String methodName = m.getName(); if (Pattern.matches(gs, methodName)) { param = getM.matcher(methodName).replaceAll(rapl).toLowerCase(); getMethods.put(param, m); } else if (Pattern.matches(ss, methodName)) { param = setM.matcher(methodName).replaceAll(rapl).toLowerCase(); setMethods.put(param, m); } else { //非get/set方法 } } } public boolean setMethodValue(String property,Object object) { Method m = setMethods.get(property.toLowerCase()); if (m != null) { try { // 调用目标类的setter函数 m.invoke(obj, object); return true; } catch (Exception ex) { ex.printStackTrace(); return false; } } return false; } }

 

最新回复(0)