I am trying to write a method which receives a serializable object (implements Serializable) o and a method m. The method should compare the state of o before invoking m and after invoking m, and tell if invoking m changed o. It should check if the bits representing o were changed after the methods. Ho can I do it?
First, correctly implement equals() (and hashCode()) on your object. You don't really need to serialize the object again. Just unserialize the original object and compare it (via equals()) to the object that you want to check for changes against.
I take it you mean:
public void checkChanged(Serializable o, Method m) { .... }
You can still do the above. Your assumption would be that the object o correctly implements equals() (and hashCode), which all objects SHOULD. You can (as other below have stated) compare the byte streams. It all depends on what you really mean by "changed".
Comparing to objects in Java is usualy made by calling equals() method. You can override this method to do the right comparison, then call it on instances before and after method call.
The other option is to compare the serialized representation of the objects
If you want to compare the serialized versions of an object, simply compare the byte arrays that the serialized objects create.
You won't be able to tell, necessarily, WHAT changed, but you will be able to tell that "something" changed.
Edit: How do you compare byte arrays?? Seriously?
public boolean same(byte b1[], byte b2[]) {
if (b1.length != b2.length) {
return false;
}
for(int i = 0; i < b1.length; i++) {
if (b1[i] != b2[i]) {
return false;
}
}
return true;
}
I mean, how else do you do it? No magic wands here.
If you check at jguru, you'll see a useful example:
Wrap an ObjectOutputStream around a ByteArrayOutputStream. Serializing an object to the ObjectOutputStream will then store the object in the byte array:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(myObject);
To restore this object, reverse the process:
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
Object myObject = ois.readObject();
If you compare the resulting byte arrays before and after the method is called, you'll be able to detect whether the object has been affected.
You can use ByteArrayInputStream and ByteArrayOutputStream to read and write your serialized objects and get their byte representations. See details in Testing object serialization.