I\'m looking for a solution to generate a checksum for any type of Java object, which remains the same for every execution of an application that produces the same object.
The Apache commons lang library provides a HashCodeBuilder
class which helps building a hash code that fills your requirements from the class properties.
Example:
public int checksum() {
// you pick a hard-coded, randomly chosen, non-zero, odd number
// ideally different for each class
return new HashCodeBuilder(17, 37).
append(property1).
append(property2).
append(property3).
toHashCode();
}
See Commons Lang API
public static String getChecksum(Serializable object) throws IOException, NoSuchAlgorithmException {
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(baos.toByteArray());
return DatatypeConverter.printHexBinary(thedigest);
} finally {
oos.close();
baos.close();
}
}
Hashcode is OK. Either given class overrides equals
and also, as contract demands, hashcode
. By contract, if equals
returns true
hashcode must be the same.
Or class doesn't override equals
. In this case different executions of your application cannot produce same object, so there is no problem.
The only problem is that some classes (even from Java API) break contract for equals
.
I had similar problem (generating good hashcode for XML files) and I found out that the best solution is to use MD5 through MessageDigest or in case you need something faster: Fast MD5. Please notice that even if Object.hashCode
would be the same every time it is anyway too short (only 32 bits) to ensure high uniqueness. I think 64 bits is a minimum to compute good hash code. Please be aware that MD5 generates 128 bits long hash code, which should is even more that needed in this situation.
Of course to use MessageDigest
you need serialize (in your case marshall) the object first.