Serializable:writeReplace

来源:互联网 发布:131458com淘宝账号查询 编辑:程序博客网 时间:2024/05/16 09:38

如果一个序列化类中含有Object writeReplace()方法,那么实际序列化的对象将是作为writeReplace方法返回值的对象,而且序列化过程的依据是实际被序列化对象的序列化实现。

People定义了writeReplace方法,并且自定义了writeObject/readObject方法。

public class People implements Serializable{    /**     *      */    private static final long serialVersionUID = 2659082826995480601L;    private int age;    private String name;    People(int age,String name)    {        this.age = age;        this.name = name;    }    private void writeObject(ObjectOutputStream out)    {        System.out.println("是否调用了我?");    }    private void readObject(ObjectInputStream in)    {        System.out.println("是否调用了我?");    }       private Object writeReplace()    {        return new Kong("路人");    }}

作为People类writeReplace返回值的Kong对象

public class Kong implements Serializable{    /**     *      */    private static final long serialVersionUID = -7144694309484327560L;    public String s;    Kong(String s)    {        this.s = s;    }    private void writeObject(ObjectOutputStream out) throws IOException    {        out.defaultWriteObject();        System.out.println("出");    }    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException    {        in.defaultReadObject();        System.out.println("入");    }}

测试程序:

@Test    public void testOut03() throws FileNotFoundException, IOException    {        People p = new People(2,"小白");        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("D:\\temp01.txt"));        out.writeObject(p);        out.flush();        out.close();    }    @Test    public void testIn03() throws FileNotFoundException, IOException, ClassNotFoundException    {        ObjectInputStream in = new ObjectInputStream(new FileInputStream("D:\\temp01.txt"));        Kong k = (Kong)in.readObject();        in.close();        System.out.println(k.s);    }

可以看到out.writeObject(p);试图序列化一个People对象,但是由于writeReplace方法的存在,实际上序列化了一个Kong 对象,在这个过程中调用了Kong定义的writeObject方法,并且在反序列化过程中,得到了一个Kong对象,并且调用了Kong定义的readObject方法。整个过程与People的writeObject/readObject无关。

这也就是说Kong k = (Kong)in.readObject();这个过程会依赖in中的实际对象,而不是依赖out.writeObject(p);

不知道为什么,就是这么个实现。

0 0
原创粉丝点击