当前位置:七道奇文章资讯编程技术Java编程
日期:2011-03-22 16:16:00  来源:本站整理

谈谈J2SE中的序列化之当序列化蒙受承当[Java编程]

赞助商链接



  本文“谈谈J2SE中的序列化之当序列化蒙受承当[Java编程]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:

当一个父类实现Serializable接口后,他的子类都将自动的实现序列化.

以下考证了这一点:

package Serial;
import java.io.Serializable;
public class SuperC implements Serializable {//父类实现了序列化
int supervalue;
public SuperC(int supervalue) {
this.supervalue = supervalue;
}
public String toString() {
return "supervalue: "+supervalue;
}
}
public class SubC extends SuperC {//子类
int subvalue;
public SubC(int supervalue,int subvalue) {
super(supervalue);
this.subvalue=subvalue;
}
public String toString() {
return super.toString()+" sub: "+subvalue;
}
}
public class Test1 {
public static void main(String [] args){
SubC subc=new SubC(100,200);
FileInputStream in=null;
FileOutputStream out=null;
ObjectInputStream oin=null;
ObjectOutputStream oout=null;
try {
out = new FileOutputStream("Test1.txt");//子类序列化
oout = new ObjectOutputStream(out);
oout.writeObject(subc);
oout.close();
oout=null;
in = new FileInputStream("Test1.txt");
oin = new ObjectInputStream(in);
SubC subc2=(SubC)oin.readObject();//子类反序列化
System.out.println(subc2);
} catch (Exception ex){
ex.printStackTrace();
} finally{
…此处省略
}
}
}

运行后果以下:

supervalue: 100 sub: 200

可见子类成功的序列化/反序列化了.

怎管让子类实现序列化看起来是一件很简单的事情,但有的时刻,常常我们不可以让父类实现Serializable接口,缘由是有时刻父类是抽象的(这并没有关系),并且父类不可以强迫每个子类都拥有序列化的本领.换句话说父类计划的目的仅仅是为了被担当.

要为一个没有实现Serializable接口的父类,编写一个可以序列化的子类是一件很麻烦的事情.java docs中提到:

“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. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime. ”


  以上是“谈谈J2SE中的序列化之当序列化蒙受承当[Java编程]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:

  • 谈谈J2SE中的序列化之当序列化蒙受承当
  • 本文地址: 与您的QQ/BBS好友分享!
    • 好的评价 如果您觉得此文章好,就请您
        0%(0)
    • 差的评价 如果您觉得此文章差,就请您
        0%(0)

    文章评论评论内容只代表网友观点,与本站立场无关!

       评论摘要(共 0 条,得分 0 分,平均 0 分) 查看完整评论
    Copyright © 2020-2022 www.xiamiku.com. All Rights Reserved .