java序列化的核心是用ObjectOutputStream讲一个对象变成一个二进制流保持,用ObjectInputStream读取的过程
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"); } }
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接口, 那么改父类的构造函数会被调用。
我们也可以用transient关键字指定一个类中个别字段不使用jvm序列化(可以选择不序列化,或自己实现该字段的序列化)
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); } }