代码如下:
public class Dog{
String name ; //狗的名字
Collar collar; //狗的类型
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Collar getCollar() {
return collar;
}
public void setCollar(Collar collar) {
this.collar = collar;
}
@Override
public String toString() {
return getName() + "是" + getCollar();
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
Dog dog = new Dog();
dog.setCollar(new Collar(5, "red"));
dog.setName("tom");
//序列化dog对象
/*FileOutputStream fos = new FileOutputStream("dog.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(dog);
oos.close();*/
//反序列化
FileInputStream fis = new FileInputStream("dog.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Object object = ois.readObject();
Dog dog1 = (Dog) object;
System.out.println("序列化对象和反序列化的对象是否是同一个对象:" + (dog == dog1));
System.out.println("序列化前的对象:" + dog.toString());
System.out.println("反序列化后的对象:" + dog1.toString());
}
}
---------------------------------------------------------------------------子类
public class Cibotium extends Dog implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String[] args){
Cibotium cibotium = new Cibotium();
cibotium.setCollar(new Collar(8, "golden"));
cibotium.setName("暖男");
try {
FileOutputStream fileOutputStream = new FileOutputStream("cibotium");
ObjectOutputStream os = new ObjectOutputStream(fileOutputStream);
os.writeObject(cibotium);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
FileInputStream fis = new FileInputStream("cibotium");
ObjectInputStream ois = new ObjectInputStream(fis);
Object object = ois.readObject();
Cibotium cibotium2 = (Cibotium) object;
ois.close();
System.out.println("序列化对象和反序列化的对象是否是同一个对象:" + (cibotium == cibotium2));
System.out.println("序列化前的对象:" + cibotium.toString());
System.out.println("反序列化后的对象:" + cibotium2.toString() + cibotium2.hashCode());
} catch (Exception e) {
e.printStackTrace();
}
}
}
-------------------------------------------------------------------------------结果为
发现反序列化后子类数据丢失,但是序列化和反序列化一切正常,求教这是为什么
在这个序列化和反序列化中,是否成功,序列化后的文件中存放了几个对象(子类和子类包含的那个对象),反序列化后,内存中有几个对象,是否有父类对象