java中串行化的例子

    技术2022-05-11  50

    下面是一个串行化的例子,程序中串行化保存name,hobby,birth和age,然而name是static的,我们将看到不能对static进行串行化,因此串行化后,改变会保持。hobby和birth是transient的,也不能串行化,但我们定义了自己的private void writeObject(ObjectOutputStream os)private void readObject(ObjectInputStream is)

    并在其中对birth进行了自定义的写入与读出,因此会看到hobby变为了null,而birth得到保存。普通变量age显然可以正常得到保存,os.defaultWriteObject();就是对其进行保存。

    同时可以看到,如果我们对某个类的对象进行串行化时,如果该类的父类没有实现Serializable接口,也就是说父类不能被串行化时,当反串行化后,会自动运行父类的构造函数,我们就是利用这个特点输出提示信息的。

    package serializetest;

    import java.io.*;

    class Base{    public Base()    {           System.out.println("下面是我的个人信息:");    }}

    public class Main extends Base implements Serializable{    static String name = null;    transient String hobby = null;    transient String birth = null;    int age = 0;        public Main()    {           name = "lcrystal";           hobby = "sleep";           birth = "1983/06/23";           age = 24;    }        public static void main(String[] args)    {        Main ts = new Main();  try {  /* 任何文件名和后缀都可以 */  FileOutputStream fos = new FileOutputStream("g://save.lc");  ObjectOutputStream os = new ObjectOutputStream(fos);    os.writeObject(ts);    os.flush();  os.close();  fos.close();   }  catch(Exception e) {  System.out.println(e.getMessage()); }   ts.name = "s0meb0dy"; ts.hobby = "sleep"; /* 我仅有的爱好!*/ ts.birth = null; ts.age = 27;  try {  FileInputStream fis = new FileInputStream("g://save.lc");  ObjectInputStream is = new ObjectInputStream(fis);    ts = (Main)is.readObject();    is.close();  fis.close();   }  catch(Exception e) {  System.out.println(e.getMessage()); }  System.out.println(ts.name); System.out.println(ts.hobby); System.out.println(ts.birth); System.out.println(ts.age);    }        private void writeObject(ObjectOutputStream os)    { try {     os.defaultWriteObject();     os.writeUTF(birth); } catch(Exception e) {     System.out.println(e.getMessage()); }    }        private void readObject(ObjectInputStream is)    { try {     is.defaultReadObject();     birth = is.readUTF(); } catch(Exception e) {     System.out.println(e.getMessage()); }    }} 


    最新回复(0)