Java序列化与Serializable(二)父类实现序列化,则子类也是可以序列化的

看下android源码中的注释:

 

父类实现序列化,子类则也可以序列化

 Android-added: Notes about serialVersionUID, using serialization judiciously, JSON.
 Serializability of a class is enabled by the class implementing the
* java.io.Serializable interface. Classes that do not implement this
* interface will not have any of their state serialized or
* deserialized.  All subtypes of a serializable class are themselves
* serializable.  The serialization interface has no methods or fields
* and serves only to identify the semantics of being serializable. <p>

翻译:实现Serializable 接口就能序列化。实现serializable的类的子类也是serializable的。

这个序列化接口没有方法或者fields,只是语法标记为可以序列化

 

上面说如果父类是序列化的,则子类也是序列化的,我们来做一个测试

父类

public class BaseBean  implements Serializable {
   public static final int serialVersionUID = 1;
   public String property1;
   public String property2;
}

子类

public class TestBean extends BaseBean  {
        public String desc;
    @Override
    public String toString() {
        return "TestBean{" +
                "desc='" + desc + '\'' +
                ", property1='" + property1 + '\'' +
                ", property2='" + property2 + '\'' +
                '}';
    }
}
测试代码
  public void serialization(View view) {
        try {

            TestBean testBean = new TestBean();
            testBean.property1 = "属性22882288";
            testBean.property2 = "属性6666";
            testBean.desc = "我是testbean";

            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();
        }
    }
实测下来,可以正常序列化和反序列化,没有问题




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值