import java.io.*;
class Person implements Serializable {
private String name;
private transient int age; // 使用transient关键字标记age字段,表示该字段不会被序列化
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
public static void main(String[] args) {
Person person = new Person("Alice", 30);
try {
// 序列化对象
FileOutputStream fileOut = new FileOutputStream("person.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(person);
out.close();
fileOut.close();
// 反序列化对象
FileInputStream fileIn = new FileInputStream("person.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Person deserializedPerson = (Person) in.readObject();
in.close();
fileIn.close();
System.out.println("Original: " + person);
System.out.println("Deserialized: " + deserializedPerson);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
transient 关键字用于标记类中的字段,表示该字段不会被序列化。在上面的代码中,age 字段被标记为 transient,因此在序列化过程中,age 字段的值不会被保存。age 字段将恢复为其默认值(对于基本类型如 int,默认值为 0;对于引用类型,默认值为 null)。age 字段的值为 0,而 name 字段的值保持不变。上一篇:java if
下一篇:java boolean默认值
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站