Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether a Java Object has been modified

Tags:

java

xml

xstream

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.

like image 908
dawww Avatar asked Mar 22 '14 13:03

dawww


People also ask

How will you check when the object is created?

Users can simply click on a particular row and see the details of that object in the “Details” panel located on the right side. It shows each and every minute information pertaining to the object such as Object Path, Object Class along with other details; such as who created the object, when and where from.

How do you test an object type?

Use the typeof operator to get the type of an object or variable in JavaScript. The typeof operator also returns the object type created with the "new" keyword. As you can see in the above example, the typeof operator returns different types for a literal string and a string object.


2 Answers

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.
like image 64
lreeder Avatar answered Oct 11 '22 21:10

lreeder


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

like image 42
bennyl Avatar answered Oct 11 '22 21:10

bennyl