import java.io.*;
class Employee implements Serializable {
public String name;
public transient int id; // 使用transient关键字标记id字段
public Employee(String name, int id) {
this.name = name;
this.id = id;
}
@Override
public String toString() {
return "Employee{name='" + name + "', id=" + id + "}";
}
public static void main(String[] args) {
Employee e = new Employee("John Doe", 12345);
try {
// 序列化对象
FileOutputStream fileOut = new FileOutputStream("employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
// 反序列化对象
FileInputStream fileIn = new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Employee e2 = (Employee) in.readObject();
in.close();
fileIn.close();
System.out.println("Deserialized Employee: " + e2);
} catch (IOException | ClassNotFoundException ex) {
ex.printStackTrace();
}
}
}
transient 关键字用于标记那些在序列化过程中不需要保存的成员变量。id 字段被标记为 transient,因此在序列化时不会被保存到文件中。当反序列化时,id 的值会恢复为默认值(对于 int 类型,默认值是 0)。Employee 对象中 id 的值为 0,而 name 仍然保留了原来的值。上一篇:java 异或
下一篇:java post
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站