1.定义
这是一个接口,当一个类实现这个接口后,这个类就变成了一个可序列化的类,它就可以被写入流,保存起来,然后也可以用流读取,反序列化。
一般情况下,一个对象会随着程序的执行完成而消失,而有时我们需要保存下来一个对象的状态,这个时候就可以把它序列化。
2.具体实现:
先定义一个Person类
class Person implements Serializable{
private static final long serialVersionUID = 1L; //一会就说这个是做什么的
String name;
int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}
public String toString(){
return "name:"+name+"\tage:"+age;
}
}
测试类Test
public class SerializableTest {
public static void main(String[] args) {
File file = new File("D:" + File.separator + "test.txt");
try (FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis)) {
Person person = new Person("tom", 22);
System.out.println(person);
oos.writeObject(person);
Person person2 = (Person) ois.readObject();
System.out.println(person2);
} catch (NotSerializableException e) {
System.out.println("NotSerializableException:" + e.getMessage());
} catch (Exception e) {
System.out.println("程序异常:" + e.getMessage());
}
}
}
输出结果:
name:tom age:22
name:tom age:22
如果Person类没有实现Serializable类,程序就会报如下错
NotSerializableException:com.example.serializable.Person
我们可以看到在Person类中定义了一个serialVersionUID,这个字段可以是1L,或者随机生成一个long类型的数据。
这个字段是这个序列化的对象的唯一标识,如果想上面的例子,序列化和反序列化都在一起,那么不会影响,如果是网络传输,那就必须保证序列化和反序列化的ID保持一致,否则会反序列化失败
3.有关静态变量的序列化
如果类的一个变量是静态的,那么它不会被序列化到流中,反序列化后这个字段会为空或者0。因为本质上序列化是针对对象的序列化,而静态变量实际上是类的属性,不是对象的属性。
4.序列化的继承
如果父类实现了Serializable接口,那么子类不需要继承,自动成为可序列化;
如果子类实现了Serializable,那么父类也实现Serializable才能被序列化
本次的代码我使用了下面这个博客的代码,写的很好,谢谢
https://blog.youkuaiyun.com/u011568312/article/details/57611440