仅实现Serializable接口的默认序列化
类实现 Serializable接口
package meng.springboot.demo.obj;import java.io.Serializable;import java.util.Date;/** * 若类仅仅实现了Serializable接口: * ObjectOutputStream 采用默认的序列化方式,对对象的非 transient 的实例变量进行序列化。 * ObjcetInputStream 采用默认的反序列化方式,对对象的非 transient 的实例变量进行反序列化。 * * @author mengzhang6 * @date 2018/10/22 8:57 */public class User implements Serializable { private int id; private String name; private Date addDate; /** * 使用transient表示,不参与序列化 */ private transient String no; /** * 声明为static和transient类型的成员数据不能被序列化 * 因为static代表类的状态,transient代表对象的临时数据。 */ public static String staNo; /** * Archive也需要实现Serializable */ private Archive archive; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getAddDate() { return addDate; } public void setAddDate(Date addDate) { this.addDate = addDate; } public String getNo() { return no; } public void setNo(String no) { this.no = no; } public Archive getArchive() { return archive; } public void setArchive(Archive archive) { this.archive = archive; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", addDate=" + addDate + ", no='" + no + '\'' + ", archive=" + archive + '}'; }}
组合类也要实现Serializable接口
package meng.springboot.demo.obj;import java.io.Serializable;/** * 档案 * * @author mengzhang6 * @date 2018/10/22 13:26 */public class Archive implements Serializable{ private String archiveNo; private String address; private transient String phone; public Archive() { } public Archive(String archiveNo, String address, String phone) { this.archiveNo = archiveNo; this.address = address; this.phone = phone; } public String getArchiveNo() { return archiveNo; } public void setArchiveNo(String archiveNo) { this.archiveNo = archiveNo; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Override public String toString() { return "Archive{" + "archiveNo='" + archiveNo + '\'' + ", address='" + address + '\'' + ", phone='" + phone + '\'' + '}'; }}
单元测试
@Test public void writeObject1() throws IOException { User user = new User(); user.setId(1001); user.setName("晨猫"); user.setAddDate(Calendar.getInstance().getTime()); user.setNo("Xs01"); user.setArchive(new Archive("Mc001","Hangzhou","18366557620")); System.out.println(user); OutputStream outputStream = new FileOutputStream(new File("User.out")); ObjectOutputStream oos = new ObjectOutputStream(outputStream); oos.writeObject(user); } @Test public void readObject1() throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("User.out")); User user = (User) ois.readObject(); System.out.println(user); }