Reputation: 340
Is it possible to serialize a runnable object in java6? I want to store the runnable object into a file.
If not, is there any other way to achieve this?
I have this class:
public abstract class SerializableRunnable implements Serializable, Runnable
{
private static final long serialVersionUID = 6217172014399079306L;
@Override
public abstract void run();
}
Then I have another class that container the previous one:
public class Action implements Serializable
{
...
private SerializableRunnable m_runnable;
@Override
public void Write(DataOutputStream dout) throws IOException
{
...
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(m_runnable);
oos.close();
byte[] m_runnableBytes = baos.toByteArray();
dout.writeInt(m_runnableBytes.length);
dout.write(m_runnableBytes);
}
...
}
The problem is that I get a java.io.NotSerializableException in this line of code:
oos.writeObject(m_runnable);
Stack trace:
java.io.NotSerializableException:
[r] at java.io.ObjectOutputStream.writeObject0(Unknown Source)
[r] at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
[r] at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
[r] at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
[r] at java.io.ObjectOutputStream.writeObject0(Unknown Source)
[r] at java.io.ObjectOutputStream.writeObject(Unknown Source)
[r] at mypackage.Action.Write(Action.java:52)
Runnable creation:
EventManager.addAction(new Action(false, EventManager.ON_EVENT_X,
new SerializableRunnable()
{
@Override
public void run()
{
// Do whatever
}
}));
Thanks in advance
EDIT: added sample code
EDIT2: added stack trace
EDIT3: added runnable creation
Upvotes: 3
Views: 5118
Reputation: 340
Thanks all for your comments.
The issue was related to what @KDM said. The class wasn't really SerializableRunnable but an anonymous class and therefore the enclosing class must be serializable too.
Upvotes: 3