Serializable接口
如果需要有序列化与反序列化支持必须实现这个接口。
代码package com.itkey.javareview.温故知新.io; import lombok.Data; import java.io.*; @Data class Person implements Serializable { private String name; private int age; private String school; public Person(String name, int age, String school) { this.name = name; this.age = age; this.school = school; } } public class 序列化与反序列化 { private static final File BINARY_FILE = new File("/Users/itkey/Documents/GitHub/java-review/src/main/java/com/itkey/javareview/温故知新/io" + File.separator+"person.ser"); public static void main(String[] args) throws Exception{ Person zxc = new Person("周星驰", 18, "不知道"); System.out.println(zxc); System.out.println("-------序列化------"); serial(zxc); System.out.println("-------反序列化------"); Object result = deSerial(); System.out.println(result); } /** * 序列化 * @param obj */ public static void serial(Object obj) throws Exception{ ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(BINARY_FILE)); oos.writeObject(obj); oos.close(); } /** * 反序列化 * @param */ public static Object deSerial() throws Exception{ ObjectInputStream ois = new ObjectInputStream(new FileInputStream(BINARY_FILE)); Object obj = ois.readObject(); ois.close(); return obj; } }transient关键字
使用方法如下:
private transient String school;
这样这个属性就不会被序列化了。