前提
由于项目需要在一条记录被更改后找到修改的内容然后记录到数据库,然后笔者找了很多网上资料木有找到所以自己写了一个Java对象比较器,废话不多说直接贴出代码贴出个性,有什么说的不对的还望各位网友指出。
代码
注解类
package com.java.test;import java.lang.annotation.Documented;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到 @Documented//说明该注解将被包含在javadoc中 public @interface Remark{ public String value(); }
比对后返回结果实体类
package com.java.test; public class Result{ public String key; public String valueFront; public String valueEnd; public Result() { super(); } public Result(String key, String valueFront, String valueEnd) { super(); this.key = key; this.valueFront = valueFront; this.valueEnd = valueEnd; }}
String 帮助类
package com.java.test;public class StringUtil { /** * 将首字母转换大写 * @param str * @return */ public static String toUpInitial(String str){ if(!StringUtil.isBlank(str)){ return str.replaceFirst(str.substring(0, 1), str.substring(0, 1).toUpperCase()); } return null; } /** * 检查字符串是否是空白:null
、空字符串""
或只有空白字符。 * ** StringUtil.isBlank(null) = true * StringUtil.isBlank("") = true * StringUtil.isBlank(" ") = true * StringUtil.isBlank("bob") = false * StringUtil.isBlank(" bob ") = false ** * @param str * 要检查的字符串 * * @return 如果为空白, 则返回true
*/ public static boolean isBlank(String str) { int length; if ((null == str) || ((length = str.length()) == 0)) { return true; } for (int i = 0; i < length; i++) { if (!Character.isWhitespace(str.charAt(i))) { return false; } } return true; }}
对象实体类
package com.java.test;public class AdminModule{ private Integer moduleId; @Remark("1235456") private String moduleName; private String moduleUrl; private String moduleRemark; public Integer getModuleId() { return moduleId; } @Remark("Test 注解测试") public String getModuleName() { return moduleName; } public void setModuleName(String moduleName) { this.moduleName = moduleName; } public String getModuleUrl() { return moduleUrl; } public void setModuleUrl(String moduleUrl) { this.moduleUrl = moduleUrl; }}
反射工具类
package com.java.test;import java.lang.annotation.Annotation;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.junit.Test;import com.alibaba.fastjson.JSON;public class ReflectUtil{ public static boolean isClass(Object obj1, Object obj2) { try { if (obj1.getClass().equals(obj2.getClass())) { return true; } } catch (Exception e) { System.err.println(e.getMessage()); } return false; } public static MapgetMethodNamesAndType(Object object) { Field[] fields = object.getClass().getDeclaredFields(); // 获取实体类的所有属性,返回Field数组 Map map = new HashMap (); for (Field field : fields) { map.put(field.getName(), field.getType().toString()); } if (map.size() == 0) { return null; } return map; } public static String[] getMethodNames(Object object) { Field[] fields = object.getClass().getDeclaredFields(); // 获取实体类的所有属性,返回Field数组 List list = new ArrayList<>(); for (Field field : fields) { list.add(field.getName()); } if (list.size() == 0) { return null; } return list.toArray(new String[list.size()]); } public static Object methodValue(Object obj, String fieldName,Class classType, Object value) { try { if(null != obj){ Class ownerClass = obj.getClass(); if (null != classType) { Method method = ownerClass.getMethod(fieldName, new Class[] { classType }); return method.invoke(obj, new Object[] { value }); } else { Method method = ownerClass.getMethod(fieldName, new Class[] {}); return method.invoke(obj, new Object[] {}); } } } catch (Exception e) { System.err.println(e.getMessage()); } return null; } public static Class getClassByClass(String str) { if (!StringUtil.isBlank(str)) { switch (str) { case "java.lang.Integer": return java.lang.Integer.class; case "java.lang.String": return java.lang.Integer.class; case "java.lang.Byte": return java.lang.Byte.class; case "java.lang.Double": return java.lang.Double.class; case "java.lang.Character": return java.lang.Character.class; case "java.util.Date": return java.util.Date.class; case "java.util.Map": return java.util.Map.class; case "java.util.List": return java.util.List.class; case "java.lang.Boolean": return java.lang.Boolean.class; default: return null; } } return null; } public static Object getNewObject(String fileName) { Class classType; try { classType = Class.forName(fileName); if(null != classType){ return classType.newInstance(); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { e.printStackTrace(); } return null; } public static List getChange(Object obj1, Object obj2) { try { if (isClass(obj1, obj2)){ if(null != obj1 && null != obj2){ Map map = getMethodNamesAndType(obj1); if(null != map && map.size() > 0){ List list = new ArrayList<>(); Result result = null; for (String key : map.keySet()) { // 方法名拼接 String fielName = "get" + StringUtil.toUpInitial(key); //通过get 方法获取字段里面的值 Object value1 = ReflectUtil.methodValue(obj1, fielName, null, null); Object value2 = ReflectUtil.methodValue(obj2, fielName, null, null); if (map.get(key).equals("java.util.List") // 判断类型是不是集合 || map.get(key).equals("java.util.MAP") || map.get(key).equals("java.util.SET")) { // TODO 集合更改未做处理 }else{ if(null == value1 || null == value2){ if(null == value1 ){ result = new Result(key, "", null == value2 ? "" : value2.toString().trim()); }else{ result = new Result(key, null == value1 ? "" : value1.toString().trim(), ""); } }else{ if (!value1.toString().trim().equals(value2.toString().trim())) { result = new Result(key, null == value1 ? "" : value1.toString().trim(), null == value2 ? "" : value2.toString().trim()); } } } if(!StringUtil.isBlank(result.getValueEnd()) && !StringUtil.isBlank(result.getValueFront())){ list.add(result); } } return list; } } } } catch (Exception e) { System.err.println(e.getMessage()); } return null; } public static Annotation getFieldAnnotation(Class classType , String name ,Class annotation) { try { if(null!= classType && null != annotation && !StringUtil.isBlank(name)){ Field field = classType.getDeclaredField(name); if(null != field){ if(field.isAnnotationPresent(annotation)){ //判断是否有此注解 return field.getAnnotation(annotation); } } } } catch (Exception e) { System.err.println(e.getMessage()); } return null; } public static Annotation getMethodAnnotation(Class classType,Class annotation,String name,Class[] parameterTypes ) { try { if(null!= classType && !StringUtil.isBlank(name)){ Method method = classType.getDeclaredMethod(name, parameterTypes); if(null != method){ if(method.isAnnotationPresent(annotation)){ //判断是否有此注解 return method.getAnnotation(annotation); } } } } catch (Exception e) { System.err.println(e.getMessage()); } return null; } @Test public void test2() throws Exception{ AdminModule module1 = new AdminModule(); AdminModule module2 = new AdminModule(); module1.setModuleId(123); module1.setModuleName("Test"); module1.setModuleUrl("sss123"); module2.setModuleId(123); module2.setModuleName("Test1"); module2.setModuleUrl("sss123"); List list = ReflectUtil.getChange(module1, module2); System.out.println("\n---------------------------------对象比对------------------------------- "); System.out.println(JSON.toJSON(list)); System.out.println("\n-----------------------------------注解----------------------------- "); Remark remark = (Remark) ReflectUtil.getFieldAnnotation(AdminModule.class, "moduleName",Remark.class ); Remark remark2 = (Remark) ReflectUtil.getMethodAnnotation(AdminModule.class, Remark.class, "getModuleName", new Class[]{}); //需要异常处理 System.out.println(remark.value()); System.out.println(remark2.value()); System.out.println("\n----------------------------------反射方法操作------------------------------ "); AdminModule module = (AdminModule) ReflectUtil.getNewObject("com.java.test.AdminModule"); ReflectUtil.methodValue(module, "setModuleName", String.class, "反射测试"); System.out.println(JSON.toJSON(module)); Object obj = ReflectUtil.methodValue(module, "getModuleName", null, null); System.out.println(obj); }}