package com.moral.api.util; import com.moral.anno.FieldName; import com.moral.pojo.CompareFieldResult; import lombok.extern.slf4j.Slf4j; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; /** * @ClassName ComparePropertyUtils * @Description TODO * @Author 陈凯裕 * @Date 2021/8/24 13:34 * @Version TODO **/ @Slf4j public class CompareFieldUtils { /** * @Description: 对比两个对象之间属性的区别 * @Param: [t, oldObject, newObject] * @return: java.util.List * @Author: 陈凯裕 * @Date: 2021/8/24 */ public static List compare(T t, Object oldObject, Object newObject) { List results = new ArrayList<>(); try { T oldObj = (T) oldObject; T newObj = (T) newObject; //获取class对象 Class TClass = oldObject.getClass(); //获取类的属性 Field[] fields = TClass.getDeclaredFields(); for (Field field : fields) { //过滤序列化信息Id if ("serialVersionUID".equals(field.getName())) { continue; } //如果没有fieldName注解则跳过 FieldName annotation = field.getAnnotation(FieldName.class); if(annotation==null) continue; //创建属性扫描器 PropertyDescriptor pd = new PropertyDescriptor(field.getName(), TClass); //获取该属性的get方法 Method readMethod = pd.getReadMethod(); //读取对象该属性的值 Object oldDataObj = readMethod.invoke(oldObj); Object newDataObj = readMethod.invoke(newObj); //如果新的值为null则证明该属性没有更新 if(newDataObj==null) continue; //如果旧值和新值相等则证明没有改变 if(oldDataObj!=null&&oldDataObj.toString().equals(newDataObj.toString())) continue; //创建返回对象 CompareFieldResult result = new CompareFieldResult(); result.setFieldName(field.getName()); result.setFieldAnnoName(annotation.value()); if(newDataObj.equals("")) result.setNewData("null"); else result.setNewData(newDataObj.toString()); if(oldDataObj==null||oldDataObj.equals("")) result.setOldData("null"); else result.setOldData(oldDataObj.toString()); results.add(result); } }catch (IntrospectionException e) { log.error(e.getMessage()); } catch (IllegalAccessException e) { log.error(e.getMessage()); } catch (InvocationTargetException e) { log.error(e.getMessage()); } return results; } /** * @Description: 将对比结果类转换为content * @Param: [results, content] content参数需要传入修改的基本描述。比如,修改了前台菜单,修改了后台角色 * @return: java.lang.String * @Author: 陈凯裕 * @Date: 2021/8/24 */ public static String resultsConvertContent(List results,String content){ StringBuilder contentReulst = new StringBuilder(content+";"); for (CompareFieldResult result : results) { contentReulst.append(result.getFieldAnnoName()+":"+result.getOldData()+"->"+result.getNewData()+";"); } return contentReulst.toString(); } }