1、记录某个实体类(表)的变化
②、 CompareClass
1 package gwm.xtkf.tool; 2 3 import java.lang.reflect.Field; 4 import java.lang.reflect.Method; 5 import java.text.SimpleDateFormat; 6 import java.util.Date; 7 import java.util.HashMap; 8 import java.util.Locale; 9 import java.util.Map; 10 11 import xs.jszx.systemmanage.domain.Purpose; 12 13 public class CompareClass { 14 15 public static String compareClass(Object from, Object target, Mapdescribe) throws Exception{ 16 17 if (from.getClass() == target.getClass()){ 18 Class c = target.getClass(); 19 Field field[] = c.getDeclaredFields(); 20 21 StringBuilder str = new StringBuilder(); 22 for (Field f: field){ 23 String type = f.getGenericType().toString(); //获取属性的类型 24 25 if (describe.get(f.getName())!=null){ 26 Object fv = invokeMethod(from, f.getName(), type); 27 Object tv = invokeMethod(target, f.getName(), type); 28 29 if (fv!=null && tv!=null){ 30 if (!fv.equals(tv)){ 31 str.append(describe.get(f.getName()) + ":" + tv + "->" + fv + ";"); 32 } 33 } 34 else if(fv==null && tv==null){} 35 else{ 36 37 if (fv!=null && fv.toString().trim().length()>0){ 38 str.append(describe.get(f.getName()) + ":" + tv + "->" + fv + ";"); 39 } 40 if (tv!=null && tv.toString().trim().length()>0){ 41 str.append(describe.get(f.getName()) + ":" + tv + "->" + fv + ";"); 42 } 43 44 } 45 } 46 47 } 48 49 return str.toString(); 50 } 51 else{ 52 return null; 53 } 54 } 55 56 @SuppressWarnings("unchecked") 57 private static Object invokeMethod(Object owner, String methodName, String type) throws Exception { 58 @SuppressWarnings("rawtypes") 59 Class ownerClass = owner.getClass(); 60 methodName = methodName.substring(0, 1).toUpperCase() 61 + methodName.substring(1); 62 Method method = null; 63 64 try { 65 method = ownerClass.getMethod("get" + methodName); 66 } catch (SecurityException e) { 67 } catch (NoSuchMethodException e) { 68 return null; 69 } 70 //如果type是类类型,则前面包含"class ",后面跟类名 71 //对日期类型进行转换 72 if(type.equals("class java.util.Date")){ 73 Date date = (Date) method.invoke(owner); 74 if(date != null){ 75 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd",Locale.US); 76 return sdf.format(date); 77 } 78 } 79 return method.invoke(owner); 80 } 81 82 public static void main(String[] args){ 83 84 Purpose purpose1 = new Purpose(); 85 Purpose purpose2 = new Purpose(); 86 87 88 purpose1.setName("住宅"); 89 purpose2.setName("别墅"); 90 91 Map map = new HashMap (); 92 map.put("name", "名称"); 93 94 try { 95 System.out.println(compareClass(purpose1, purpose2, map)); 96 } catch (Exception e) { 97 // TODO Auto-generated catch block 98 e.printStackTrace(); 99 }100 }101 }