比较实现
我这里提供一个,目前我看到的,最简单的比较两个对象属性是否一致的方法,废话不多说,直接上代码,一看就懂:
package design.decorator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.alibaba.fastjson.JSON;
public class Test {
private final static String[] strDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e",
"f" };
public static void main(String[] args) {
// 测试代码
Object obj = new Object();
Object newObj = new Object();
String model = JSON.toJSONString(obj);
String newModel = JSON.toJSONString(newObj);
String strModel = getMD5(model);
String strNewModel = getMD5(newModel);
System.out.println("两个对象是否相等:" + obj.equals(newObj));
System.out.println("两个对象属性是否相等:" + strNewModel.equals(strModel));
}
/**
* 获取MD5摘要数据
*
* @return String
*/
public static String getMD5(String pwd) {
String nPwd = "";
try {
// 返回实现指定摘要算法的 MessageDigest 对象。这里是用MD5加密
MessageDigest md = MessageDigest.getInstance("MD5");
// 调用digest() 方法完成哈希计算,并将字节数组转化为字符串
nPwd = byteToString(md.digest(pwd.getBytes()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return nPwd;
}
/**
* 将字节数组转化为字符串
*
* @param bytes
* bytes
* @return String
*/
private static String byteToString(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
sb.append(byteToArrayString(bytes[i]));
}
return sb.toString();
}
/**
* 将字节转化为字符串
*
* @param bByte
* bByte
* @return String
*/
private static String byteToArrayString(byte bByte) {
int temp = bByte;
if (temp < 0) {
temp += 256;
}
int index1 = temp / 16;
int index2 = temp % 16;
return strDigits[index1] + strDigits[index2];
}
}
运行结果: