java对象序列化
用于网络传输该对象
要序列化的对象Person
序列化的对象必须实现
Serializable
接口, 否则序列化会报错
class Person implements Serializable {
String name = "Li";
int age = 10;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void show() {
System.out.println("this is the show 方法!!");
}
public void printInfo() {
System.out.println("姓名是: " + name + " 年龄是: " + age);
}
}
序列化过程
使用
new ObjectOutputStream
进行写入到文件中
public static void main(String[] args) {
FileOutputStream fileOutputStream = new FileOutputStream("D:\\java_project\\jpa-test\\src\\main\\java\\com\\example\\controller\\b.txt");
new ObjectOutputStream(fileOutputStream).writeObject(new Person("Person-name",22));
}
序列化后的文件打开内容如下:
反序列化过程
public static void main(String[] args) {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("D:\\java_project\\jpa-test\\src\\main\\java\\com\\example\\controller\\b.txt"));
Person person = (Person) objectInputStream.readObject();
System.out.println(person.age);
System.out.println(person.name);
person.show();
person.printInfo();
}
打印结果:
如果序列化后修改了原始对象Person,如,新增加了一个方法, 则反序列化失败
class Person implements Serializable {
String name = "Li";
int age = 10;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void show() {
System.out.println("this is the show 方法.");
}
public void printInfo() {
System.out.println("姓名是: " + name + " 年龄是: " + age);
}
//新增了一个方法
public void addNewFunc() {
System.out.println("添加了一个新方法...");
}
}
反序列化失败:
如果想确保在序列化后,修改序列化对象后, 在反序列化时不报错, 需要序列化对象加上
private static final long serialVersionUID = 64623316465L;
现在Person类如下:
class Person implements Serializable { //加上序列化号 private static final long serialVersionUID = 64623316465L; String name = "Li"; int age = 10; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public void show() { System.out.println("this is the show 方法."); } public void printInfo() { System.out.println("姓名是: " + name + " 年龄是: " + age); } public void addNewFunc() { System.out.println("添加了一个新方法..."); } }
现在再次序列化后,再修改Person对象,然后再反序列化就不会报错了