Is there a way I can copy an object to a file while debugging so that I can use it later for testing? I am using java on eclipse. Specifically I waned to copy the request object for making junits
-
Please take a look: stackoverflow.com/questions/15407944/…Shreyos Adikari– Shreyos Adikari2013-04-04 14:24:50 +00:00Commented Apr 4, 2013 at 14:24
-
You can copy objects as strings in eclipse,they are output of toString() method.BlackJoker– BlackJoker2013-04-04 14:28:50 +00:00Commented Apr 4, 2013 at 14:28
-
@ Shreyos Adikari I dont think I can use the approach in that question for a request objectRegisteredUser– RegisteredUser2013-04-04 14:31:28 +00:00Commented Apr 4, 2013 at 14:31
-
@ Spring.Rush The request object has Objects toString() ... it just prints referenceRegisteredUser– RegisteredUser2013-04-04 14:32:13 +00:00Commented Apr 4, 2013 at 14:32
-
Is this something you can use a mock for instead?Blake– Blake2013-04-04 14:35:09 +00:00Commented Apr 4, 2013 at 14:35
1 Answer
If your object's class (or any of its superclasses) implements interface java.io.Serilizable, you can easily serialize this object and store it in a file. Let's say you have an object:
MyClass myObj = new MyClass();
Just open 'Display' view in Eclipse (Window -> Show view -> Other... -> Debug/Display) and type:
java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(new java.io.FileOutputStream("/path/to/your/file"));
oos.writeObject(myObj);
oos.close();
Select this code and press Ctrl+i - Eclipse will execute code, so myObj will be stored in the file (in this case, "/path/to/your/file"). Use canonical names of classes from java.io package in a Display view, because this package may be not imported in the class whis is currently being executed.
Later, you can restore this object (say, in a test class):
import java.io.*;
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("/path/to/your/file"));
MyClass myObj = (MyClass) ois.readObject();
ois.close();
Of course, you should wrap this in usual try/catch/finally stuff to avoid resorce leaks.
Unfortunately, this won't work if MyClass doesn't implement java.io.Serializable interface.