在Java中,transient
关键字用于标记对象中的某个字段,使其在序列化时不被持久化到输出流中。当对象被反序列化时,被transient
修饰的字段将不会被恢复其原始值,而是会被设置为该类型的默认值(例如,对于引用类型,默认值为null
)。
transient关键字的作用
- 序列化忽略:
transient
关键字告诉Java序列化机制在序列化时忽略该字段。 - 节省存储空间:对于那些不需要持久化的字段,使用
transient
可以避免不必要的序列化和反序列化,从而节省存储空间。 - 保护敏感数据:对于包含敏感信息的字段,使用
transient
可以防止这些信息被意外地序列化到磁盘或其他持久化存储中。
下面用一个简单的示例,演示了如何使用transient
关键字:
import java.io.*;public class Employee implements Serializable {private String name;private transient int salary; // 不被序列化private String department;public Employee(String name, int salary, String department) {this.name = name;this.salary = salary;this.department = department;}// Getter and Setter methodspublic String getName() {return name;}public void setName(String name) {this.name = name;}public int getSalary() {return salary;}public void setSalary(int salary) {this.salary = salary;}public String getDepartment() {return department;}public void setDepartment(String department) {this.department = department;}@Overridepublic String toString() {return "Employee{" +"name='" + name + '\'' +", salary=" + salary +", department='" + department + '\'' +'}';}
}class SerializationExample {public static void main(String[] args) {try {// 创建 Employee 对象Employee emp = new Employee("John Doe", 50000, "Engineering");// 序列化FileOutputStream fos = new FileOutputStream("employee.ser");ObjectOutputStream oos = new ObjectOutputStream(fos);oos.writeObject(emp);oos.close();// 反序列化FileInputStream fis = new FileInputStream("employee.ser");ObjectInputStream ois = new ObjectInputStream(fis);Employee deserializedEmp = (Employee) ois.readObject();ois.close();// 输出反序列化后的对象System.out.println(deserializedEmp);} catch (IOException | ClassNotFoundException e) {e.printStackTrace();}}
}
运行上述代码时的输出:
Employee{name='John Doe', salary=0, department='Engineering'}
代码说明
-
Employee 类:
Employee
类实现了Serializable
接口,使其可以被序列化。salary
字段被标记为transient
,意味着它不会被序列化到文件中。
-
序列化和反序列化:
- 创建了一个
Employee
对象,并将其序列化到文件employee.ser
中。 - 从文件中反序列化
Employee
对象。 - 注意到
salary
字段在反序列化后被设置为默认值0
。
- 创建了一个
所以transient
关键字可以用来控制哪些字段应该被序列化,这对于保护敏感信息或节省存储空间都非常有用。