How to generate a checksum for an java object

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

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

提交回复
热议问题