在java中序列化对象需要实现一个接口,表示该对象可以被序列化
java.io.Serializable
接下来介绍一个关键字
transient
这个关键字的意思就是取反:
如果一个对象实现了Serializable接口,加上这个关键字表示这个对象不能被序列化;
如果一个对象没有实现Serializable接口,加上这个关键字表示这个对象可以被序列化,同时需要告诉虚拟机应该如何序列化,在类的内部写两个方法。
1// 注:这些方法定义时必须是私有的,因为不需要你显示调用,序列化机制会自动调用的 2private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException; 3private void writeObject(ObjectOutputStream out) throws IOException;
栗子:

完整栗子:
1package top.swimmer.tokenizer; 2 3import java.time.LocalDateTime; 4 5public class Foo { 6 private String a; 7 private LocalDateTime time; 8 9 public String getA() { 10 return a; 11 } 12 13 public void setA(String a) { 14 this.a = a; 15 } 16 17 public LocalDateTime getTime() { 18 return time; 19 } 20 21 public void setTime(LocalDateTime time) { 22 this.time = time; 23 } 24 25 public Foo() { 26 a = "Hello world!"; 27 time = LocalDateTime.now(); 28 } 29} 30 31 32package top.swimmer.tokenizer; 33 34import java.io.Closeable; 35import java.io.IOException; 36import java.io.ObjectInputStream; 37import java.io.ObjectOutputStream; 38import java.io.Serializable; 39import java.time.LocalDateTime; 40 41public class Too implements Serializable, Closeable { 42 private transient Foo foo; // Foo没有实现Serializable接口,但是加了transient关键字就可以被序列化了 43 private String c; 44 45 public Too() { 46 c = "Good man!"; 47 foo = new Foo(); 48 } 49 50 @Override 51 public void close() throws IOException { 52 System.out.println("too close"); 53 } 54 55 // 要写两个方法供虚拟机调用,分别告诉虚拟机对于Foo对象如何写,如何读 56 private void writeObject(ObjectOutputStream out) throws IOException { 57 out.defaultWriteObject(); 58 out.writeObject(foo.getA()); 59 out.writeObject(foo.getTime()); 60 } 61 62 private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { 63 input.defaultReadObject(); 64 Foo foo = new Foo(); 65 foo.setA((String) input.readObject()); 66 foo.setTime((LocalDateTime) input.readObject()); 67 this.foo = foo; 68 } 69} 70 71 72package top.swimmer.tokenizer; 73 74import java.io.File; 75import java.io.FileInputStream; 76import java.io.FileOutputStream; 77import java.io.ObjectInputStream; 78import java.io.ObjectOutputStream; 79 80public class ObjectDemo { 81 public static void main(String[] args) throws Exception { 82 Too t = new Too(); 83 File file = new File(ObjectDemo.class.getResource("/aaa.json").getFile()); 84 85 ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file)); 86 output.writeObject(t); 87 ObjectInputStream input = new ObjectInputStream(new FileInputStream(file)); 88 Too t1 = (Too) input.readObject(); 89 System.out.println(); 90 } 91}