自定义类实现序列化和反序列化
-
要想一个java对象可序列化,必须满足如下要求:
- 需要实现接口:Serializable
- 当前类提供一个全局常量:serialVersionUID
- 除了当前Person类需要实现Serializable接口之外,还必须保证其内部的所有属性也必须是可序列化的(默认情况下基本数据类型是可序列化的)
-
不可序列化static和transient修饰的成员变量
-
序列化
package com.ran; import java.io.Serializable; public class Person implements Serializable { public static final long serialVersionUID = 646548943165464L; private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } public Person(String name, int age) { this.name = name; this.age = age; } public Person() { } }
package com.ran;
import java.io.*;
public class Ran {
public static void main(String[] args) {
ObjectOutputStream oos = null;
try {
FileOutputStream fos = new FileOutputStream("object.dat");
oos = new ObjectOutputStream(fos);
oos.writeObject(new String("我爱北京天安门"));
oos.writeObject(new String("冉海锋",21));
} catch (IOException e) {
e.printStackTrace();
} finally {
if(oos!=null){
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
-
反序列化
package com.ran; import java.io.*; public class Ran { public static void main(String[] args) { ObjectInputStream ois = null; try { FileInputStream fis = new FileInputStream("object.dat"); ois = new ObjectInputStream(fis); Object obj = ois.readObject(); String str=(String)obj; Person p = (Person) ois.readObject(); System.out.println(str); System.out.println(p); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if(ois!=null){ try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } } } }