Alex
Alex

Reputation: 4073

How to generate a checksum for an java object

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.

Upvotes: 22

Views: 58594

Answers (11)

Narasimha
Narasimha

Reputation: 17

/*
 * Calculate checksum of a File using MD5 algorithm
 */
public static String checkSumApacheCommons(Object obj){
    String checksum = DigestUtils.md5Hex(String.valueOf(obj));
    return checksum;
}

Upvotes: 0

FRotthowe
FRotthowe

Reputation: 3662

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

Upvotes: 2

Evgeny Nozdrev
Evgeny Nozdrev

Reputation: 1566

  1. Object -> String (For example, GSON - you will not have to write serialization not to list all fields of your class)

  2. String.hashCode() -> int (Instead of Object.hashCode()! This realization of hashCode() depends on content of String, not on address in memory --- you can use it across different app launches, different threads, etc.)

(or 2. String -> md5)

Upvotes: 0

Leonardo Leitão
Leonardo Leitão

Reputation: 191

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();
    }
}

Upvotes: 17

PeterB
PeterB

Reputation: 323

Example

private BigInteger checksum(Object obj) throws IOException, NoSuchAlgorithmException {

    if (obj == null) {
      return BigInteger.ZERO;   
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(obj);
    oos.close();

    MessageDigest m = MessageDigest.getInstance("SHA1");
    m.update(baos.toByteArray());

    return new BigInteger(1, m.digest());
}

Upvotes: 8

pillingworth
pillingworth

Reputation: 3238

If you're f you're using Eclipse IDE then it has actions (under Source menu) to generate hashcode and equals functions. It allows you to choose the attributes of the class you want in the hashcode. This is similar to using the HashCodeBuilder approach that has already been suggested.

Alternatively you could stream the object to a byte array and generate an MD5 of that.

Upvotes: 2

kopper
kopper

Reputation: 2736

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.

Upvotes: 17

Tadeusz Kopec for Ukraine
Tadeusz Kopec for Ukraine

Reputation: 12403

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.

Upvotes: 2

Joachim Sauer
Joachim Sauer

Reputation: 308001

Do you want to be able to do this for all Java objects?

In that case hashCode() doesn't work.

For some classes hashCode() has a stricter definition which guarantees equality across executions. For example String has a well-defined hashCode implementation. Similarly List and Set have well-defined values, provided all objects that they contain also have well-defined values (note that the general Collection.hashCode() does not require the value to be well-defined).

For other classes you will have to use reflection recursively with some well-defined formula to build a checksum.

Upvotes: 3

Seffi
Seffi

Reputation: 204

If you control the source, you can implement hashCode() so it will be consistent from one execution to another.

Upvotes: 4

Roman
Roman

Reputation: 66156

I think you should look at serialization. Serialization mechanism needs to solve similar problem, so you can look how it's implemented.

But if you describe the problem you're trying to solve you'll probably get more precise solution.

Upvotes: 5

Related Questions