10

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

7
  • Please take a look: stackoverflow.com/questions/15407944/… Commented Apr 4, 2013 at 14:24
  • You can copy objects as strings in eclipse,they are output of toString() method. Commented Apr 4, 2013 at 14:28
  • @ Shreyos Adikari I dont think I can use the approach in that question for a request object Commented Apr 4, 2013 at 14:31
  • @ Spring.Rush The request object has Objects toString() ... it just prints reference Commented Apr 4, 2013 at 14:32
  • Is this something you can use a mock for instead? Commented Apr 4, 2013 at 14:35

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

yeah myclass is not serializable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.