java为什么我没有得到NotSerializableException?
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。木卫一。运行时的NotSerializableException。因为MyClass
具有类的引用,该类不实现可序列化接口!到底发生了什么
# 1 楼答案
因为该字段为空。和null可以很好地序列化
序列化机制检查每个字段的实际具体类型,而不是其声明的类型。您可以有一个NotSerializable子类的实例,即Serializable,然后它也可以很好地序列化。如果不是这样,您将无法序列化任何具有类型为
List
的成员的对象,例如,因为List
没有实现可序列化