Java custom serialization: writeReplace() and readResolve() methods
The writeReplace
and readResolve
methods in Java allow you to customize the serialization and deserialization process of an object.
writeReplace
is called during the serialization process. This method provides an opportunity to replace the object being serialized with another object. The object returned by this method will be serialized instead of the original object.readResolve
is called during the deserialization process. This method provides an opportunity to replace the deserialized object with another object. The object returned by this method will be returned as the result of the deserialization process instead of the deserialized object.
Here’s an example of how you can use the writeReplace
and readResolve
methods for custom serialization in Java:
import java.io.Serializable;
class User implements Serializable {
private static final long serialVersionUID = 1L;
private String username;
private String password;
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
private Object writeReplace() {
return new UserInfo(username);
}
private Object readResolve() {
return new User(username, "****");
}
}
class UserInfo implements Serializable {
private static final long serialVersionUID = 1L;
private String username;
public UserInfo(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
}
In this example, the User
class implements the Serializable
interface. During the serialization process, the writeReplace
method is called and returns an instance of the UserInfo
class instead of the original User
object. The UserInfo
class only contains the username information and doesn’t have the password information.
During the deserialization process, the readResolve
method is called and returns a new instance of the User
class with the password set to "****"
. This way, the password information is not serialized or deserialized.