在java中序列化对象需要实现一个接口,表示该对象可以被序列化
java.io.Serializable
接下来介绍一个关键字
transient
这个关键字的意思就是取反:
如果一个对象实现了Serializable接口,加上这个关键字表示这个对象不能被序列化;
如果一个对象没有实现Serializable接口,加上这个关键字表示这个对象可以被序列化,同时需要告诉虚拟机应该如何序列化,在类的内部写两个方法。
// 注:这些方法定义时必须是私有的,因为不需要你显示调用,序列化机制会自动调用的
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;
private void writeObject(ObjectOutputStream out) throws IOException;
栗子:
完整栗子:
package top.swimmer.tokenizer;
import java.time.LocalDateTime;
public class Foo {
private String a;
private LocalDateTime time;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public LocalDateTime getTime() {
return time;
}
public void setTime(LocalDateTime time) {
this.time = time;
}
public Foo() {
a = "Hello world!";
time = LocalDateTime.now();
}
}
package top.swimmer.tokenizer;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.time.LocalDateTime;
public class Too implements Serializable, Closeable {
private transient Foo foo; // Foo没有实现Serializable接口,但是加了transient关键字就可以被序列化了
private String c;
public Too() {
c = "Good man!";
foo = new Foo();
}
@Override
public void close() throws IOException {
System.out.println("too close");
}
// 要写两个方法供虚拟机调用,分别告诉虚拟机对于Foo对象如何写,如何读
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeObject(foo.getA());
out.writeObject(foo.getTime());
}
private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
input.defaultReadObject();
Foo foo = new Foo();
foo.setA((String) input.readObject());
foo.setTime((LocalDateTime) input.readObject());
this.foo = foo;
}
}
package top.swimmer.tokenizer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ObjectDemo {
public static void main(String[] args) throws Exception {
Too t = new Too();
File file = new File(ObjectDemo.class.getResource("/aaa.json").getFile());
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file));
output.writeObject(t);
ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
Too t1 = (Too) input.readObject();
System.out.println();
}
}