参考:一文搞懂序列化与反序列化 - 知乎 (zhihu.com)
一、jdk序列化和反序列化
module结构:
FactInfo.java
package com.hmb; import java.io.Serial; import java.io.Serializable; public class FactInfo implements Serializable { @Serial private static final long serialVersionUID = 8059875275354456501L; private Integer id; private String name; public FactInfo(Integer id, String name) { this.id = id; this.name = name; } @Override public String toString() { return "[" + id.toString() + name.toString() + "]"; } }
TestBean.java
package com.hmb; import java.io.Serial; import java.io.Serializable; import java.util.Date; import java.util.List; public class TestBean implements Serializable { @Serial private static final long serialVersionUID = -444249457751783736L; private Integer id; private String name; private Date date; private FactInfo factInfo; public void setFactInfos(List<FactInfo> factInfos) { this.factInfos = factInfos; } private List<FactInfo> factInfos; public TestBean(Integer id, String name, Date date, FactInfo factInfo) { this.id = id; this.name = name; this.date = date; this.factInfo = factInfo; } @Override public String toString() { String factinfoStr = ""; for (FactInfo factInfo : factInfos) { factinfoStr += factInfo.toString(); } return id.toString() + name.toString() + date.toString() + factInfo.toString() + factinfoStr; } }
Main.java
package com.hmb; import java.io.*; import java.util.Date; import java.util.LinkedList; import java.util.List; public class Main { public static void main(String[] args) { TestBean testBean = new TestBean(1, "zhangsan", new Date(), new FactInfo(1, "fact1")); List<FactInfo> factInfos = new LinkedList<>(); factInfos.add(new FactInfo(2, "fact2")); factInfos.add(new FactInfo(3, "fact3")); testBean.setFactInfos(factInfos); FileOutputStream fileOutputStream; try { System.out.println(testBean.toString()); fileOutputStream = new FileOutputStream("test.txt"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); objectOutputStream.writeObject(testBean); ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("test.txt")); TestBean testBean1 = (TestBean) objectInputStream.readObject(); System.out.println(testBean1.toString()); } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } }
运行效果:
标签:java,name,demo,toString,import,new,序列化,id From: https://www.cnblogs.com/hemeiwolong/p/17476348.html