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?
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".
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.
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.
Related
Is there an easy way to save all the values of variables in scala REPL?
There is :save command in scala but it just saves the history of commands and the next time we need to recalculate everything from scratch.
I know that I can manually serialize/de-serialize everything I'm interested in, but there are two main difficulties (also applicable to java):
It is hard to manually write serialize/de-serialize code for every defined (Serializeable) variable and it is not extensible for later use.
It is only possible to save Serializable objects. I know that saving (hibernating) an arbitrary object may results in problems (especially for objects working with external resources), but whether there would be a problem or not, depends on the state of the program. Sometimes the programmer is sure that in the current situation there would be no problem saving the variables. I think there should be a way for the programmer to take the responsibility of saving everything, even the objects not explicitly defined Serializable.
I appreciate answers solving any of these problems.
Someone thought it would be a good idea to store Objects in the database in a blob column using Java's default serialization methods.
The structure of these objects is controlled by another group and they changed a field type from BigDecimal to a Long,
but the data in our database remains the same.
Now we can't read the objects back because it causes ClassCastExceptions.
I tried to override it by writing my own readObject method,
but that throws a StreamCorruptedException because what was written by the default writeObject method.
How do I make my readObject call behave like Java's default one?
Is there a certain number of bytes I can skip to get to my data?
Externalizable allows you to take full control of serialization/deserialization. But it means you're responsible for writing and reading every field,
When it gets difficult though is when something was written out using the default serialization and you want to read it via Externalizable. (Or rather, it's impossible. If you try to read an object serialized with the default method using Externalizable, it'll just throw an exception.)
If you've got absolutely no control on the output, your only option is to keep two versions of the class: use the default deserialization of the old version, then convert to the new. The upside of this solution is that it keeps the "dirty" code in one place, separate from your nice and clean objects.
Again, unless you want to do things really complicated, your best option is to keep the old class as the "transport" bean and rename the class your code really uses to something else.
If you want to read what's already in your database your only option is to get them to change the class back again, and to institute some awareness that you're relying on the class definition as it was when the class was serialized. Merely implementing your own readObject() call can't fix this, and if the class is under someone else's control you can't do that anyway.
If you're prepared to throw away the existing data you have many other choices starting with custom Serialization, writeReplace()/readResolve(), Externalizable, ... or a different mechanism such as XML.
But if you're going to have third parties changing things whenever they feel like it you're always going to have problems of one kind or another.
BigDecimal to Long sounds like a retrograde step anyway.
Implement the readObject and readObjectNoData methods in you class.
Read the appropriate type using ObjectInoutStream.readObject and convert it to the new type
See the Serializable interface API for details.
More Details
You can only fix this easily if you control the source of the class that was serialized into the blob.
If you do not control this class,
then you have only a few limited and difficult options:
Have the controlling party give you a version of the class that reads the old format and writes the new format.
Write you own form of serialization (as in you read the blob and convert the bytes to classes) that can read the old format and generate new versions of the classes.
Write you own version of the class in question (remove the other from the class path) which reads the old format and produces some intermediate form (perhaps JSON).
Next you have to do one of these
Convince the powers that be that the blob technique is shitty and should be done away with. use the current class change as evidance. Almost any technique is better that this. Writing JSON to the db in the blob is better.
Stop depending on shitty classes from other people. (shitty is a judgement which I can only suspect, not know, is true). Instead create a suite of classes that represent the data in the database and convert from the externally controlled classes to the new data classes before writing to the database.
I am doing a java project and have several methods. Would like to know if its possible to quit the programme after the 3rd method for example and then when resuming the programme it continues from there? Any information regarding this would be helpful
THank you
Not without some kind of external persistence mechanism, no.
Once the process is done, it's done.
Why do you want to do this? There may be a better solution.
Otherwise, it would be along the lines of saving data in some particular format (JSON, YAML, etc..) and then have a parser that could determine where the last program left off. It's somewhat vague, so it also depends on what you're attempting to "save".
Potentially could do something hacky if you ran the program with a wrapper.
Edit:
You could serialize your classes, which in turn would allow you to be able to save the fields of any objects you have, however everything you have would need to implement Serializable and be saved to a file.
So after a little bit of googling, I found that there is also the XStream library, which serializes objects to XML without needing to implement an interface. In that sense, you could serialize objects themselves, but wouldn't be able to, say, continue from the middle of a method. (Having a string you can parse to start in different locations could be one option).
I have a requirement, where support in my application a lot of processing is happening, at some point of time an exception occrured, due to an object. Now I would like to know the whole history of that object. I mean whatever happened with that object over the period of time since the application has started.
Is this peeping into this history of Object possible thru anyway using JMX or anything else ?
Thanks
In one word: No
With a few more words:
The JVM does not keep any history on any object past its current state, except for very little information related to garbage collection and perhaps some method call metrics needed for the HotSpot optimizer. Doing otherwise would imply a huge processing and memory overhead. There is also the question of granularity; do you log field changes only? Every method call? Every CPU instruction during a method call? The JVM simply takes the easy way out and does none of the above.
You have to isolate the class and/or specific instance of that object and log any operation that you need on your own. You will probably have to do that manually - I have yet to find a bytecode instrumentation library that would allow me to insert logging code at runtime...
Alternatively, you might be able to use an instrumenting profiler, but be prepared for a huge performance drop when doing that.
That's not possible with standard Java (or any other programming language I'm aware of). You should add sufficient logging to your application, which will allow you to get some idea of what's happened. Also, learn to use your IDE's debugger if you don't already know how.
I generally agree with #thkala and #artbristol (+1 for both).
But you have a requirement and have no choice: you need a solution.
I'd recommend you to try to wrap your objects with dynamic proxies that perform auditing, i.e. write all changes that happen to object.
You can probably use AspectJ for this. The aspect will note what method was called and what are the parameters that were sent. You can also use other, lower level tools, e.g. Javasist or CgLib.
Answer is No.JVM doesn't mainatain the history of object's state.Maximum what you can do you can keep track of states of your object that could be some where in-memory and when you get exception you can serialize that in-memory object and then i think you can do analysis.
I want to hook the method System.out.print in Java and have the ability to read/change the variables used in the method before the part of the method is called that actually adds the string to whatever the output stream is.
In C++ I would just detour the function, or set an int3 instruction so I could access the registers but in java I have no idea how to accomplish something similar.
You can rewrite the byte code of the methods, and in the process capture/change the local variables. It is not trivial. See some notes here.
Maybe what you really want is a java debugger? You can connect a debugger to a remote process, add a breakpoint, and capture/change the local variables pretty easily using eclipse.
What is the real problem you are trying to solve?
Have a look at this link.
He sneakily defines a static anonymous class so that System.out points to something different, and therefore print and println will route through that object.
You can reassign System.out (and System.err) to another object which does what you want to do with it. Said object usually gets the old System.out value so that output can be made in the end.
This is usually done in main() and influences the whole JVM.
We use this to have automatic wrapping at 130 columns in a very peculiar setting where longer lines are truncated.
Since JDK 1.1, the System.setOut and System.setErr methods are added to enable applications to hook the streams.
Link : http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#setOut(java.io.PrintStream)
http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#setErr(java.io.PrintStream)
#Nowayz Some time before i too had the same problem with me.
After some research i came to know About AOP. AOP i.e. AspectJ provides a facility to intercept the java APIs by applying the pointcuts before,after, around. So have a look at it .You can refer my question on stack .it may help you.