Anuja Barve
Anuja Barve

Reputation: 320

Generating Checksum for Java Object

I have a Java class that implements Serializable:

Class A implements Serializable {
    public String name;
    int contact;
}

I store this Java object in mongodb. How can I generate a checksum for this Java object?

public String generateChecksum throws Exception(A object){
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     ObjectOutputStream oos = new ObjectOutputStream(baos);
     oos.writeObject(object);

     MessageDigest md = MessageDigest.getInstance("MD5");
     byte[] thedigest = md.digest(baos.toByteArray());
     String hex =  DatatypeConverter.printHexBinary(thedigest);
     System.out.println(hex);
}

I am getting a

Null Pointer Exception at oos.writeObject(object).

Is there a better way to do this??

Upvotes: 1

Views: 2175

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533492

Unless you have specific requirements for the checksum, the simplest approach is to use a hashCode.

@Override
public int hashCode() {
    return Objects.hash(name, contact);
}

public static String hashCodeString(Object a) {
    return Integer.toHexString(a.hashCode());
}

Upvotes: 2

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

The problem appears to be that your code does not compile.

Class A implements Serializable {


public String generateChecksum throws Exception(A object){

Upvotes: 1

Related Questions