这是我的小班:
import java.io.Serializable;
public abstract class SerializableCallback extends Callback
implements Serializable {
private static final long serialVersionUID = 4544768712188843966L;
public abstract void handleMessage(Message msg);
}
这是它更小的父级Callback
:
public abstract class Callback {
public abstract void handleMessage(Message msg);
}
这是我的测试:
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() {}
测试NotSerializableException
在注释指示的行上给了我一个。这里有几件事肯定不能引起:
- 缺少可序列化声明
- 不可序列化的字段:根本没有字段
- 最接近的不可序列化父类型的不可见非参数构造函数
那么导致异常的原因是什么?