transient
在Java中,transient 是一个关键字,用于声明一个字段不会被序列化。
当一个对象被序列化时,被声明为 transient 的字段将不会被保存到序列化的结果中
主要用途:
- 敏感信息隐藏: transient 可以用于隐藏对象中的敏感信息,确保它们不会被持久化到存储设备或通过网络传输
- 临时数据: 有些字段在持久化时不需要被保存,比如缓存或临时计算的数据
注意事项:
- transient 只能用于字段,不能用于类或方法
- 被声明为 transient 的字段在反序列化时会被设置为默认值,如 null(对于对象)、0(对于基本数据类型)或 false(对于布尔类型)
- 序列化过程中,transient 字段的内容不会被保存到序列化结果中
- transient 只影响对象的序列化,不影响其它方面的行为,比如字段的访问权限等
示例
import java.io.*;
class Person implements Serializable {
private String name;
private transient String password; // 密码字段被声明为 transient
public Person(String name, String password) {
this.name = name;
this.password = password;
}
// Getters and setters
public String getName() {
return name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
public class TransientExample {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person person = new Person("Alice", "123456");
// 序列化对象
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.ser"));
out.writeObject(person);
out.close();
// 反序列化对象
ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.ser"));
Person deserializedPerson = (Person) in.readObject();
in.close();
// 输出反序列化后的对象
System.out.println("姓名:" + deserializedPerson.getName());
System.out.println("密码:" + deserializedPerson.getPassword()); // 密码字段为 null
}
}