serialVersionUID是干什么用的
2017-09-14 本文已影响0人
海边的贝壳林
序列化
使Java的对象可以序列化, 但是为什么需要这个id呢. 这个序列化的对象, 在写入(序列化)和读取(反序列化)的时候有可能存在差异. 那么Java就用这个serialVersionUID
值是否相同来判断序列化的对象是否一致. 如果两个对象的serialVersionUID
都不一致, 那肯定就没办法序列化了.
例子
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = 7371845487964803604L;
private String name;
private int id;
public Person(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", id=" + id +
'}';
}
}
序列化
import java.io.*;
public class DeserialTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person person;
FileInputStream fileInputStream = new FileInputStream("person.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
person = (Person)objectInputStream.readObject();
System.out.println(person);
}
}
反序列化
import java.io.*;
public class DeserialTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person person;
FileInputStream fileInputStream = new FileInputStream("person.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
person = (Person)objectInputStream.readObject();
System.out.println(person);
}
}