Serializable:readResolve

如果序列化类定义了Object readResolve() ,那么将无视readObject的实现,直接返回作为readResolve() 方法返回值的对象。

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;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private void writeObject(ObjectOutputStream out)
    {
        System.out.println("是否调用了我?");
    }
    private void readObject(ObjectInputStream in)
    {
        System.out.println("是否调用了我?");
    }

    private Object readResolve() 
    {
        return new People(20,"老子喜欢刚正面");
    }

}

测试程序:

@Test
public void testOut01() throws FileNotFoundException, IOException
{
    People p = new People(100,"老汉");
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("D:\\temp01.txt"));
    out.writeObject(p);
    out.flush();
    out.close();
}

@Test
public void testIn01() throws FileNotFoundException, IOException, ClassNotFoundException
{
    ObjectInputStream in = new ObjectInputStream(new FileInputStream("D:\\temp01.txt"));
    People p = (People)in.readObject();
    in.close();
    System.out.println(p.getAge());
    System.out.println(p.getName());

}

People p = (People)in.readObject();拿到了

private Object readResolve() 
{
    return new People(20,"老子喜欢刚正面");
}

这个对象,尽管writeObject/readObject什么都没做。
在这个过程中writeObject/readObject仍然在序列话和反序列化过程中被调用。

阅读更多
文章标签: 序列化
个人分类: java
上一篇Serializable:自定义序列化
下一篇Serializable:writeReplace
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭