How to generate a checksum for an java object

后端 未结 10 790
生来不讨喜
生来不讨喜 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:39

    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

提交回复
热议问题