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

代码如下:

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();

}

}

}

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

5157368688ff35f0adb8ecd209b1e098.png

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值