learning java transient 自定义序例化
public class Person implements java.io.Serializable { private String name; private transient int age; // 注意此处没有提供无参数的构造器! public Person(String name, int age) { System.out.println("有参数的构造器"); this.name = name; this.age = age; } // 省略name与age的setter和getter方法 // name的setter和getter方法 public void setName(String name) { this.name = name; } public String getName() { return this.name; } // age的setter和getter方法 public void setAge(int age) { this.age = age; } public int getAge() { return this.age; } }
TransientTest
public class TransientTest { public static void main(String[] args) { try ( // 创建一个ObjectOutputStream输出流 var oos = new ObjectOutputStream(new FileOutputStream("transient.txt")); // 创建一个ObjectInputStream输入流 var ois = new ObjectInputStream(new FileInputStream("transient.txt"))) { var per = new Person("孙悟空", 500); // 系统会per对象转换字节序列并输出 oos.writeObject(per); var p = (Person) ois.readObject();
//notes: p.getAge == 0 System.out.println(p.getAge()); } catch (Exception ex) { ex.printStackTrace(); } } }