Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy object from eclipse debugger

Tags:

java

eclipse

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

like image 941
RegisteredUser Avatar asked Apr 04 '13 14:04

RegisteredUser


1 Answers

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.

like image 176
Grzegorz Olszewski Avatar answered Oct 18 '22 18:10

Grzegorz Olszewski