java 序列化父类属性_Java序列化与Serializable(四)父类实现如果未实现序列化,子类如何序列化父类的field...

看源码的注释,有这么一句

To allow subtypes of non-serializable classes to be serialized, the * subtype may assume responsibility for saving and restoring the * state of the supertype's public, protected, and (if accessible) * package fields.

也就是说,如果父类没有序列化,父类的field又想要参与子类的序列化过程,则这个过程要子类来完成

看代码 public class BaseBean { public String property1; public String property2; public int property3; public BaseBean(String id){ } public BaseBean(){} } public class TestBean extends BaseBean implements Serializable { public String desc; public static final int serialVersionUID = 1; public TestBean(String id) { super(id); } @Override public String toString() { return "TestBean{" + "desc='" + desc + '\'' + ", property1='" + property1 + '\'' + ", property2='" + property2 + '\'' + ", property3=" + property3 + '}'; } private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.defaultWriteObject();//先序列化对象 out.writeUTF(property1);//再序列化父类的域 out.writeUTF(property2); out.writeInt(property3); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject();//先反序列化对象 property1 = in.readUTF();//再反序列化父类的域 property2 = in.readUTF(); property3= in.readInt(); } } public void serialization(View view) { try { TestBean testBean = new TestBean(""); testBean.property1 = "属性88999988-property1__"; testBean.property2 = "属性88999988-property2__"; testBean.desc = "我是testbean88999988-desc__"; testBean.property3 = 88888803; ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("/sdcard/aaatest.txt")); objectOutputStream.writeObject(testBean); } catch (IOException e) { e.printStackTrace(); } } public void deserialization(View view) { ObjectInputStream objectInputStream = null; try { objectInputStream = new ObjectInputStream(new FileInputStream("/sdcard/aaatest.txt")); TestBean testBean = (TestBean) objectInputStream.readObject(); Log.i(TAG,"deserialization"+testBean.toString()); } catch (Exception e) { e.printStackTrace(); } }

通过定制序列化和反序列化过程。则父类的field也可以参与子类的序列化过程了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值