序列化接口的作用:没有方法,不需要覆盖,是一个标记接口为了启动一个序列化功能
唯一作用,给每一个需要序列化的类都分配一个serialVersionUID 的版本号
这个版本号和该类相关联.
这个版本号的作用:
在反序列过程中用于验证序列化对象的发送者和接收者是否为该对象加载流于序列化兼容的类.如果不同,则会导致InvalidClassException
是用于验证的
import java.io.*;
public class ObjectInputStreamTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
//需求:想要将封装流数据的对象进行持久化.当写入的对象很多,对象会按照顺序排列,也称之为对象的序列化
//1.应该先有对象.Person
writeObj();
readObj();
}
public static void writeObj() throws IOException { //对象的序列化
Person p = new Person("lisi",20);
FileOutputStream fos = new FileOutputStream("tempfile/obj.object");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(p);
oos.close();
fos.close();
}
public static void readObj() throws IOException, ClassNotFoundException { //对象反序列化
FileInputStream fis = new FileInputStream("tempfile/obj.object");
ObjectInputStream ois = new ObjectInputStream(fis);
Object obj = ois.readObject();
System.out.println(obj.toString());
ois.close();
fis.close();
}
}
class Person implements Serializable { //实现序列化接口
private static final long serialVersionUID = 12345;//自定义序列号
private static String name; // 静态数据不会被序列化
private transient int age; //对于非静态的数据也不想序列化,瞬态关键字transient
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}