views:

139

answers:

3

I just had an idea that I wonder whether is possible in java. Let's say when doing debugging using eclipse or netbeans, you could record an object and save it. Then when going through the second round of debugging, save the object again. Now you could compare the first object recorded with the second object for all properties and find out any differences. Is this possible?

+3  A: 

You can do this in plain Java code (assuming your objects are Serializable), but I don't think any debuggers have this feature built-in.

It would simply be a case of serialising the first object during the debugging run (which if you had a static method to do so, you could generally call from the debugger) and saving it somewhere. Then, during the second run, call another method to reconstitute the object from it's serialised form - and then compare the objects (either with their equals() methods, or some more bespoke comparison method).

In practice though I find that whenever I want to do this I just scribble down the relevant properties on a piece of paper and compare them manually. Rarely am I looking at thousands and thousands of properties that might change between a run; if you think about the symptoms you're seeing and the behaviour of your object, you can normally have a very good idea of what might be changing before you even fire up the debugger, and then use the latter to confirm your hypothesis and backtrack to see where the value "went wrong".

Andrzej Doyle
i did like what you do as well write down on paper. and looking for more professional way of doing it
cometta
+1  A: 

Give your object a useful toString() method and then use unit tests to compare the result with what you expect.

But I agree: The wire protocol for remote debugging can serialize any object, so it should be possible to write a program that does this automatically.

OTOH, objects which aren't meant to be serialized can be dangerous. If you accidentally use this on a classloader, you'll get all objects and classes and everything back as one big lump. So you need a way to stop the serialization to make sure it can't run havoc in a deep object tree.

On top of that, I'd like a feature to save the current state of the app and be able to go back in time.

Aaron Digulla
+1  A: 

I don't think any debugger can save object to compare them later. What you can do though is to create a watch variable on the variable, but wrap it with the ToStringBuilder() of the apache commons and dump it in the console, like so:

System.out.println(ToStringBuilder.reflectionToString(object));

Each time the breakpoint is reached, the content of the object will be shown in the console. You can even see the private data.

Therefore, you do not need to modify the toString() method of the object directly (this is useful for library object for example). You can then compare the output of your two passes.

Thierry-Dimitri Roy
look cool technique to me. thank for pointing this out
cometta