Here’s my tiny class:
import java.io.Serializable;
public abstract class SerializableCallback extends Callback
implements Serializable {
private static final long serialVersionUID = 4544768712188843966L;
public abstract void handleMessage(Message msg);
}
Here’s its even tinier parent Callback:
public abstract class Callback {
public abstract void handleMessage(Message msg);
}
And here’s my test:
public void testSerialization() throws IOException, ClassNotFoundException {
SerializableCallback c = new SerializableCallback() {
private static final long serialVersionUID = -4852385037064234702L;
@Override
public void handleMessage(Message msg) {
callbackMethod();
}
};
FileOutputStream fos = new FileOutputStream(FILE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(c); // fails
out.close();
FileInputStream fis = new FileInputStream(FILE);
ObjectInputStream in = new ObjectInputStream(fis);
Object object = in.readObject();
@SuppressWarnings("unused")
SerializableCallback d = (SerializableCallback) object;
}
private void callbackMethod() {}
The test gives me a NotSerializableException on the line indicated by a comment. Here’s a couple of things by which it can certainly not be caused:
- Missing Serializable declaration
- Non-serializable fields: there are no fields at all
- Invisible non-arg constructor of closest non-serializable parent type
So what does cause the exception?
Your class doesn’t have a no-arg constructor. It has a constructor which takes one argument which is the
thisof the outer class. If you made testSerialization()staticit might fix the problem.But I suspect your immediate real problem is that your nest class has a reference to the outer class and the outer class is not Serializable.