class NotSerializable {}
class MyClass implements Serializable {
private NotSerializable field; // class NotSerializable does not implement Serializable!!
}
public class Runner {
public static void main(String[] args) {
MyClass ob = new MyClass();
try {
FileOutputStream fs = new FileOutputStream("testSer.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(ob);
os.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis = new FileInputStream("testSer.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
MyClass copyOb = (MyClass) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
该程序正确执行并成功序列化对象ob
。但我希望在运行时得到java.io.NotSerializableException。因为MyClass
有没有实现 Serializable 接口的类的引用!到底发生了什么?