import java.io.*;
class Employee implements Serializable {
// 普通字段
private String name;
private int age;
// 使用 transient 关键字修饰的字段,表示该字段不会被序列化
private transient String password;
// 构造函数
public Employee(String name, int age, String password) {
this.name = name;
this.age = age;
this.password = password;
}
// 打印员工信息的方法
public void printInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Password: " + (password == null ? "Not available" : password));
}
public static void main(String[] args) {
// 创建一个 Employee 对象
Employee emp = new Employee("Alice", 30, "secret");
// 序列化对象到文件
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("employee.ser"))) {
oos.writeObject(emp);
System.out.println("Object has been serialized");
} catch (IOException e) {
e.printStackTrace();
}
// 反序列化对象从文件
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("employee.ser"))) {
Employee deserializedEmp = (Employee) ois.readObject();
System.out.println("Object has been deserialized");
deserializedEmp.printInfo();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
transient
关键字:在 Java 中,transient
关键字用于修饰类的成员变量,表示该变量不会被序列化。当对象被序列化时,transient
变量的值不会被保存到磁盘或传输到其他地方。
序列化和反序列化:
示例代码中的 Employee
类:
name
和 age
是普通的实例变量,会被序列化。password
是用 transient
关键字修饰的变量,因此在序列化时不会被保存。输出结果:
password
的值会变成 null
,因为它是 transient
的,没有被序列化保存。通过这个例子可以清楚地看到 transient
关键字的作用。
上一篇:java contains
下一篇:java枚举
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站