java序列化的核心是用ObjectOutputStream讲一个对象变成一个二进制流保持,用ObjectInputStream读取的过程

Java序列化接口

class c implements Serializable {

    private static final long serialVersionUID = 2087368867376448459L;
    private String s = new String("123");


    @Override
    public String toString() {
        return s;
    }

    private  void writeObject(ObjectOutputStream ois) {
        System.out.println("write");
    }
    private void readObject(ObjectInputStream ois){
        System.out.println("read");
    }
}

Java外部化接口

class c implements Externalizable {

    private static final long serialVersionUID = 2087368867376448459L;
    private String s = new String("123");

    public c(){}

    @Override
    public String toString() {
        return s;
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        System.out.println("write");
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        System.out.println("read");
    }
}

对子类对象进行反序列化时, 如果其父类没有实现Serializable接口, 那么改父类的构造函数会被调用。

import java.io.*;


class Foo  implements Serializable{
    public String user;
    public String name;

    public Foo(String u,String n){
        super();
        this.user=u;
        this.name=n;
    }
}
public class io {
    public static void main(String args[]) throws IOException, ClassNotFoundException {

        ObjectOutputStream i = new ObjectOutputStream(new FileOutputStream("aa.bat"));
        i.writeObject(new Foo("aa","bb"));
        i.close();
        ObjectInputStream j = new ObjectInputStream(new FileInputStream("aa.bat"));
        Foo f = (Foo)j.readObject();
        j.close();
        System.out.println(f.user+" : "+f.name);

    }
}