Java序列化、反序列化知多少
https://mp.weixin.qq.com/s/0EfIUB9E-0Oh_Clwuxswuw
普通类
import java.io.Serializable;
public class Student implements Serializable {
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 "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
单例类
import java.io.Serializable;
public class Singleton implements Serializable {
private Singleton() {
}
private static class SingletonHolder {
private static final Singleton SINGLETON = new Singleton();
}
public static synchronized Singleton getSingleton() {
return SingletonHolder.SINGLETON;
}
/**
* 在单例类中手写readResolve()函数,直接返回单例对象。防止反序列化后,对象比较不一致问题
* readObject() 序列化会自动调用
*
* @return
*/
private Object readResolve() {
return SingletonHolder.SINGLETON;
}
}
注意:readResolve()方法
import java.io.*;
public class ClassSerializeUtils {
public static <T extends Serializable> boolean serialize(File file, T obj) {
if (obj == null) {
return false;
}
try {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
oos.writeObject(obj);
}
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static <T> T deserialize(File file, Class<T> tClass) throws IOException, ClassNotFoundException {
if (!(file != null && file.isFile() && file.exists())) {
throw new IllegalArgumentException("Please check if the file is correct!");
}
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
return (T) ois.readObject();
}
}
}
demo:
// 普通类序列化示例
private static void demo1() throws IOException {
Student student = new Student();
student.setAge(123);
student.setName("zhangsan");
File file = new File("C:\\Users\\mbh\\Downloads\\student.txt");
boolean serialize = ClassSerializeUtils.serialize(file, student);
if (serialize) {
System.out.println(" student,序列化成功 ");
}
try {
Student student1 = ClassSerializeUtils.deserialize(file, Student.class);
System.out.println(student1.getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//单例类序列化示例
private static void demo2() throws IOException {
// 单例序列化保证一致性
File file = new File("C:\\Users\\mbh\\Downloads\\singleton.txt");
boolean serialize = ClassSerializeUtils.serialize(file, Singleton.getSingleton());
if (serialize) {
System.out.println(" 单例列 singleton,序列化成功 ");
}
try {
Singleton singleton1 = ClassSerializeUtils.deserialize(file, Singleton.class);
System.out.println(Singleton.getSingleton() == singleton1);
// 单例类保证与序列化前一致 true
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}