思路
- 标记敏感字段:使用
transient
关键字标记敏感信息字段,这样在默认序列化时这些字段不会被写入字节流。
- 自定义序列化方法:实现
writeObject
方法,手动控制序列化过程,不写入敏感字段。
- 自定义反序列化方法:实现
readObject
方法,在反序列化后重新填充敏感信息。
关键代码示例
import java.io.*;
public class SensitiveClass implements Serializable {
private String normalField = "Normal Data";
private transient String password;
public SensitiveClass(String password) {
this.password = password;
}
// 自定义序列化方法
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
// 不写入password字段
}
// 自定义反序列化方法
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
// 反序列化后重新填充敏感信息
this.password = "Re - filled Password";
}
public static void main(String[] args) {
SensitiveClass obj = new SensitiveClass("Original Password");
// 序列化
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("sensitive.ser"))) {
oos.writeObject(obj);
} catch (IOException e) {
e.printStackTrace();
}
// 反序列化
SensitiveClass deserializedObj;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("sensitive.ser"))) {
deserializedObj = (SensitiveClass) ois.readObject();
System.out.println("Normal Field: " + deserializedObj.normalField);
System.out.println("Password: " + deserializedObj.password);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}