- 作用
实现这个接口的类可以被序列化和反序列化,也就是以二进制流的形式存储在文件中,或者从文件中重建类对象。
package com.hjx.search_engine.entity;
import java.io.Serializable;
public class Demo implements Serializable {
// private static final long serialVersionUID = 1L;
private String id;
private String name;
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String tag;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
return "Demo{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", tag='" + tag + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.hjx.search_engine;
import com.hjx.search_engine.entity.Demo;
import java.io.*;
public class TestSerializable {
private static void serialize(Object o) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("file.txt")));
oos.writeObject(o);
System.out.println("序列化成功");
oos.close();
}
private static Demo deserialize(String filename) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(filename)));
Demo demo = (Demo)ois.readObject();
ois.close();
System.out.println("反序列化成功");
return demo;
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
Demo demo = new Demo();
demo.setId("123");
demo.setName("hjx");
serialize(demo);
Demo demo1 = deserialize("file.txt");
System.out.println(demo1.toString());
}
}
运行结果:
- serialVersionUID作用
- 在序列化类对象后,类代码可能发生变化,如果前后类代码的serialVersionUID一致,那么即使类源码发生变化,也能后反序列化类文件。如果不一致,反序列化一定不能进行。会产生
java.io.InvalidClassException
- 如果没有该字段,则JVM会根据类的属性字段自动生成serialVersionUID,同时也跟JVM版本有关,所以在不同的机器上,很可能相同类序列化后也不能被反序列化。