How to generate a checksum for an java object

后端 未结 10 773
生来不讨喜
生来不讨喜 2020-12-13 01:04

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.

相关标签:
10条回答
  • 2020-12-13 01:30

    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.

    0 讨论(0)
  • 2020-12-13 01:30

    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.

    0 讨论(0)
  • 2020-12-13 01:33

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

    0 讨论(0)
  • 2020-12-13 01:34

    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.

    0 讨论(0)
  • 2020-12-13 01:36

    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());
    }
    
    0 讨论(0)
  • 2020-12-13 01:37
    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)

    0 讨论(0)
提交回复
热议问题