How to generate a checksum for an java object

Alex picture Alex · Apr 15, 2010 · Viewed 45.1k times · Source

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.

I tried it with Object.hashCode(), but the api says

....This integer need not remain consistent from one execution of an application to another execution of the same application.

Answer

Leonardo Leitão picture Leonardo Leitão · Mar 18, 2015
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();
    }
}