关闭

Serializable:readResolve

标签: 序列化
169人阅读 评论(0) 收藏 举报
分类:

如果序列化类定义了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仍然在序列话和反序列化过程中被调用。

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场