首页 新闻 会员 周边 捐助

关于Java序列化 父类未序列化,子类序列化 子类数据丢失

0
悬赏园豆:5 [待解决问题]

代码如下:
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();
    }   
}

}
-------------------------------------------------------------------------------结果为

发现反序列化后子类数据丢失,但是序列化和反序列化一切正常,求教这是为什么

问题补充:

在这个序列化和反序列化中,是否成功,序列化后的文件中存放了几个对象(子类和子类包含的那个对象),反序列化后,内存中有几个对象,是否有父类对象

十月十四的主页 十月十四 | 初学一级 | 园豆:197
提问于:2019-01-02 23:46
< >
分享
所有回答(1)
0
全力以赴001 | 园豆:629 (小虾三级) | 2019-01-03 09:38
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册