我无法理解Serialization
Java 1.6 的基础知识。
下面是Dog
包含类实例变量的Collar
类:
狗.java
public class Dog implements Serializable {
private Collar collar;
public Collar getCollar() {
return collar;
}
public void setCollar(Collar collar) {
this.collar = collar;
}
}
Collar 类没有实现Serializable
如下所示的接口:
领子.java
public class Collar {
private int size;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
现在,当我尝试序列化时,Dog
为什么它不抛出一个NotSerializableException
?根据合同,整个对象图应该实现Serializable
,但我的Collar
班级没有实现。
下面是这个demo的主要方法:
public static void main(String[] args) {
try {
FileOutputStream fs = new FileOutputStream("E:\\test.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
Dog dog = new Dog();
// No exception thrown here, WHY?
// test.ser file is getting created properly.
os.writeObject(dog);
FileInputStream fis = new FileInputStream("E:\\test.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Dog dog1 = (Dog)ois.readObject();
// Here I am getting a null Collar object
Collar c1 = dog1.getCollar();
请解释一下,在尝试实现所有理论内容时我完全感到困惑:(