- 必须实现序列化接口 - 声明UID
- 属性私有化,并且声明get/set方法
- 声明无参和有参构造函数
- 重写hashCode和equals方法
- 重写toString方法
拓展:
transient关键字在序列化中的使用:这是一个修饰符,被修饰的属性可以在序列化中被忽略
在某些特定的业务场景会使用
封装一个person类
package Test21_Demo.Demo05;/*
@create 2020--12--14--10:18
*/
import java.io.Serializable;
import java.util.Objects;
public class Person_up implements Serializable {
private static final long serialVersionUID = -5779259024239172808L;
//定义的普通表示码 - 普通版本码
//private static final long SerialVersionUID = 1L;
private String name;
//这个age就不会被序列化
private transient int age;
public Person_up() {
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", 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;
}
public Person_up(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Person_up)) return false;
Person_up personUp = (Person_up) o;
return getAge() == personUp.getAge() &&
Objects.equals(getName(), personUp.getName());
}
@Override
public int hashCode() {
return Objects.hash(getName(), getAge());
}
}
序列化
package Test21_Demo.Demo05;/*
@create 2020--12--14--10:33
*/
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class SerializableDemo {
public static void main(String[] args) throws IOException {
//准备被序列化的对象
Person_up person = new Person_up("Jack.Ma", 18);
//进行序列化操作
FileOutputStream fos = new FileOutputStream("person_up.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//开始序列化
oos.writeObject(person);
//关闭流a
oos.close();
}
}
反序列化
package Test21_Demo.Demo05;/*
@create 2020--12--14--10:33
*/
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class SerializableDemo2 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
//进行反序列化操作
FileInputStream fis = new FileInputStream("person_up.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
//开始反序列化
Person_up person_up = (Person_up) ois.readObject();
System.out.println(person_up.getName() + " " + person_up.getAge());//Jack.Ma 0
System.out.println(person_up);//Person{name='Jack.Ma', age=0}
//关闭流
ois.close();
}
}