import java.io.*;
class Employee implements Serializable {
// transient关键字用于声明不希望被序列化的变量
private transient String password;
private String name;
public Employee(String name, String password) {
this.name = name;
this.password = password;
}
@Override
public String toString() {
return "Employee{name='" + name + "', password='" + password + "'}";
}
public static void main(String[] args) {
Employee emp = new Employee("John Doe", "secret");
// 序列化对象
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("employee.ser"))) {
oos.writeObject(emp);
System.out.println("Object has been serialized");
// 反序列化对象
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("employee.ser"))) {
Employee deserializedEmp = (Employee) ois.readObject();
System.out.println("Deserialized object: " + deserializedEmp);
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
transient 关键字用于声明不希望被序列化的变量。在上面的代码中,password 字段被标记为 transient,因此在序列化过程中不会被保存到文件中。password 字段将不会恢复其原始值,而是保持为默认值(对于字符串类型,默认值是 null)。上一篇:java获取当前时间年月日时分秒
下一篇:java json转对象
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站