Java serialization: readObject() vs. readResolve()

前端 未结 10 964
花落未央
花落未央 2020-12-02 04:07

The book Effective Java and other sources provide a pretty good explanation on how and when to use the readObject() method when working with serializable Java class

10条回答
  •  情歌与酒
    2020-12-02 04:24

    When serialization is used to convert an object so that it can be saved in file, we can trigger a method, readResolve(). The method is private and is kept in the same class whose object is being retrieved while deserialization. It ensures that after the deserialization, what object is returned is the same as was serialised. That is, instanceSer.hashCode() == instanceDeSer.hashCode()

    readResolve() method is not a static method. After in.readObject() is called while deserialisation it just makes sure that the returned object is the same as the one which was serialized as below while out.writeObject(instanceSer)

    ..
        ObjectOutput out = new ObjectOutputStream(new FileOutputStream("file1.ser"));
        out.writeObject(instanceSer);
        out.close();
    

    In this way, it also helps in singleton design pattern implementation, because every time same instance is returned.

    public static ABCSingleton getInstance(){
        return ABCSingleton.instance; //instance is static 
    }
    

提交回复
热议问题