-
序列化:把对象写入到硬盘或网络中的过程。
-
反序列化:把硬盘或网络的二进制文件读取到内存形成对象的过程。
把Person对象使用对象源写入硬盘中
要求:
- 序列化的类心须实现Serializable (自动序列化接口) ,Externglizable. ( 手动序列化接口)
- 序列化的类要添加一个私有的long类型静态常量:serverVersionUID,保证序列化的类反序列化的类是同一个类。
注意实现:
(1)使用transient修饰的属性,不可以序列化
(2)静态属性不能被序列化
public class Person implements Serializable {
// 如果不写,会自动生成
private static final Long serialVersionUID = 1258L;
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = 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 class SerializableTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
writeObject();
readObject();
}
/**
* 序列化
*/
public static void writeObject() throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream("D:\\myTemp\\temp3.bin");
ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream);
ArrayList<Person> list = new ArrayList<>();
Person person1 = new Person("zbx", 21);
Person person2 = new Person("bao", 20);
list.add(person1);
list.add(person2);
// 序列化
outputStream.writeObject(list);
System.out.println("序列化成功");
outputStream.close();
}
/**
* 反序列化
*/
public static void readObject() throws IOException, ClassNotFoundException {
FileInputStream fileInputStream = new FileInputStream("D:\\myTemp\\temp3.bin");
ObjectInputStream inputStream = new ObjectInputStream(fileInputStream);
// 反序列化
ArrayList<Person> list = (ArrayList<Person>) inputStream.readObject();
for (Person person : list) {
System.out.println(person);
}
System.out.println("反序列化完成");
inputStream.close();
}
}
使用transient修饰的属性,一定不可以序列化吗?
答:不一定,可以使用手动序列化
实现Externalizable,手动实现序列化
public class Person implements Externalizable {
重写两个方法
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(name);
out.writeObject(age);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
name = (String) in.readObject();
age = (int) in.readObject();
}
此时,使用transient修饰的属性,就可以被序列化了