Java序列化、反序列化知多少

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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值