比较一个类的两个对象是否相同

    由于工作需要,写了个比较两个对象是否相同的类,即对象的属性值是否相同,属性值通过getXxx()、isXxx()方法得到,如属性无get、is方法,则该属性会被过滤掉,属性不包括list,map等容器类。

    原理是利用set的唯一性验证两个对象的同一个属性值是否相同。若相同,continue;不同,break。若属性是自定义数组,则递归该数组。

    另,本代码是jdk1.4的,jdk1.5需要改动下面红色的部分,将null参数去掉即可。

 

package test;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Iterator;

/**
 * <li>Title: Test.java</li>
 * <li>Project: Test</li>
 * <li>Package: test</li>
 * <li>Description: </li>
 * <li>Copyright: Copyright (c) 2009</li>
 * <li>Company: IdealTechnologies </li>
 * <li>Created on May 8, 2009 12:48:17 PM</li>
 *
 * @author chun_chang
 * @version 1.0
 */
public class Test {

 private static Set set = new HashSet();

 public static void main(String[] args) {
  A a = new A();
  A b = new A("2", 1);
  if (compare(a, b)) {
   System.out.println(a + " and " + b + " are same ...");
  } else {
   System.out.println(a + " and " + b + " are different ...");
  }
 }

/**
  * @param obj1
  * @param obj2
  * @return false different,true same
  * @CreateOn May 8, 2009 2:53:27 PM
  * @author chun_chang
  */
 public static boolean compare(Object obj1, Object obj2) {
  boolean isSame = false;
  boolean isPrimitive = false;
  try {
   Map map1 = getGetMethod(obj1);
   Map map2 = getGetMethod(obj2);
   Iterator iter = map1.keySet().iterator();
   while (iter.hasNext()) {
    String key = (String) iter.next();
    Object[] o1 = (Object[]) map1.get(key);
    Object[] o2 = (Object[]) map2.get(key);

    isPrimitive = ((Class) o1[1]).isPrimitive();
    if (isPrimitive) {
     set.add(o1[0]);
     isSame = !set.add(o2[0]);
     if (set.size() != 1) {
      System.out.println("the method '" + key + "()' is different ...");
      set.clear();
      break;
     } else {
      set.clear();
     }
    } else {
     Class c = (Class) o1[1];
     String objClass = c.toString().split(" ")[1];
     if (objClass.startsWith("java.")) {
      set.add(o1[0]);
      isSame = !set.add(o2[0]);
      if (set.size() != 1) {
       System.out.println("the method '" + key + "()' is different ...");
       set.clear();
       break;
      } else {
       set.clear();
      }
     } else if (c.isArray()) {// String array
      if ("[Ljava.lang.String;".equals(objClass)) {
       if (o1[0] != null && o2[0] != null) {
        for (int k = 0; k < ((String[]) o1[0]).length; k++) {
         if (((String[]) o1[0])[k] != ((String[]) o2[0])[k]) {
          isSame = false;
          System.out.println("the method '" + key + "()' is different ...");
          break;
         }
        }
       } else if (o1[0] == null && o2[0] == null) {
        isSame = true;
        continue;
       } else {
        System.out.println("the method '" + key + "()' is different ...");
        isSame = false;
        continue;
       }
      } else if (objClass.length() == 2) {// base array
       char ch = objClass.charAt(1);
       switch (ch) {
       case 'Z':// boolean
        for (int k = 0; k < o1.length; k++) {
         if (((boolean[]) o1[0])[k] != ((boolean[]) o2[0])[k]) {
          System.out.println("the method '" + key + "()' is different ...");
          isSame = false;
          break;
         }
        }
        break;
       case 'B':// byte
        for (int k = 0; k < o1.length; k++) {
         if (((byte[]) o1[0])[k] != ((byte[]) o2[0])[k]) {
          System.out.println("the method '" + key + "()' is different ...");
          isSame = false;
          break;
         }
        }
        break;
       case 'C':// char
        for (int k = 0; k < o1.length; k++) {
         if (((char[]) o1[0])[k] != ((char[]) o2[0])[k]) {
          System.out.println("the method '" + key + "()' is different ...");
          isSame = false;
          break;
         }
        }
        break;
       case 'D':// double
        for (int k = 0; k < o1.length; k++) {
         if (((double[]) o1[0])[k] != ((double[]) o2[0])[k]) {
          System.out.println("the method '" + key + "()' is different ...");
          isSame = false;
          break;
         }
        }
        break;
       case 'F':// float
        for (int k = 0; k < o1.length; k++) {
         if (((float[]) o1[0])[k] != ((float[]) o2[0])[k]) {
          System.out.println("the method '" + key + "()' is different ...");
          isSame = false;
          break;
         }
        }
        break;
       case 'I':// int
        for (int k = 0; k < o1.length; k++) {
         if (((int[]) o1[0])[k] != ((int[]) o2[0])[k]) {
          System.out.println("the method '" + key + "()' is different ...");
          isSame = false;
          break;
         }
        }
        break;
       case 'J':// long
        for (int k = 0; k < o1.length; k++) {
         if (((long[]) o1[0])[k] != ((long[]) o2[0])[k]) {
          System.out.println("the method '" + key + "()' is different ...");
          isSame = false;
          break;
         }
        }
        break;
       case 'S':// short
        for (int k = 0; k < o1.length; k++) {
         if (((short[]) o1[0])[k] != ((short[]) o2[0])[k]) {
          System.out.println("the method '" + key + "()' is different ...");
          isSame = false;
          break;
         }
        }
        break;
       }
      } else {// customer array
       if (o1[0] != null && o2[0] != null) {
        for (int k = 0; k < ((Object[]) o1[0]).length; k++) {
         if (o1[0] != null && o2[0] != null) {
          isSame = compare(((Object[]) o1[0])[k], ((Object[]) o1[0])[k]);
         } else if (o1[0] == null && o2[0] == null) {
          isSame = true;
          continue;
         } else {
          System.out.println("the method '" + key + "()' is different ...");
          isSame = false;
          continue;
         }
        }
       } else if (o1[0] == null && o2[0] == null) {
        isSame = true;
        continue;
       } else {
        System.out.println("the method '" + key + "()' is different ...");
        isSame = false;
        continue;
       }
      }
     } else {
      if (o1[0] != null && o2[0] != null) {
       isSame = compare(o1[0], o2[0]);
      } else if (o1[0] == null && o2[0] == null) {
       isSame = true;
       continue;
      } else {
       System.out.println("the method '" + key + "()' is different ...");
       isSame = false;
       continue;
      }
     }
    }

   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return isSame;
 }

 /**
  * get <code>getXxx()</code>
  *
  * @param object
  * @return
  * @throws Exception
  * @CreateOn May 8, 2009 2:27:46 PM
  * @author chun_chang
  */
 private static Map getGetMethod(final Object object) throws Exception {
  Method[] methods = object.getClass().getDeclaredMethods();
  Map map = new HashMap();
  for (int i = 0; i < methods.length; i++) {
   String method = methods[i].getName();
   if ("get".equals(method.substring(0, 3)) || "is".equals(method.substring(0, 2))) {
    Object objArr[] = new Object[2];
    objArr[0] = invokeMethod(object, method);
    objArr[1] = methods[i].getReturnType();
    map.put(method, objArr);
   }
  }
  return map;
 }

 /**
  * get the value of attribute
  *
  * @param obj
  * @param methodName
  * @return
  * @throws Exception
  * @CreateOn May 8, 2009 1:39:41 PM
  * @author chun_chang
  * @throws Exception
  */
 private static Object invokeMethod(Object obj, String methodName) throws Exception {
  Class ownerClass = obj.getClass();
  Method method = null;
  try {
   method = ownerClass.getMethod(methodName, null);
  } catch (NoSuchMethodException e) {
   System.out.println("error: can't find '" + methodName + "' method ...");
  } catch (Exception e) {
   e.printStackTrace();
  }
  return method.invoke(obj, null);
 }

}

 

若谁有更好的办法,欢迎一起探讨,MSN:changchun08521@hotmail.com

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值