Question

I would like to use a clean/automatic way to check if a Java Object has been modified.
My specific problem is the following:

In my Java application, I use XStream library to deserialize XML to Java Objects, then the user can modify or change them. I'd like a way to check if these Objects in memory are at some point different from the serialized ones, so I can inform the user and ask him if he want to save the changes (i.e. serialize using XStream) or not. In my application there are many Objects and are quite complex.

Please consider that I don't use databases in my application, so I'm not interested in solutions like using hibernate.

Was it helpful?

Solution

Two approaches:

  • Implement a hashcode for your objects, and compare the hashcode of the in-memory objects against the hashcode of the serialized objects to see if they've been changed. This is has a low impact on your class design, but performance will go down as O(n^2) as the number of objects increases. Note that two objects might return the same hashcode, but a good hashing implementation will make this very unlikely. If you are concerned about this, implement and use your own equals() method.
  • Have your objects implement the Observer pattern and have each setter method, or any other method that modifies the object, notify the observer when it's called. Performance will be better for large numbers of objects (as long as they aren't changing constantly), but it requires you to introduce Observer code into possibly lightweight classes. Java provides a utility interface for Observable, but you'll still need to do most of the work.

OTHER TIPS

You can store a version field in this object, whenever the object changed it should update its version field (increment it), you can then compare the version field with the serialized object version field

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top