关于Serializable接口

103 阅读1分钟

Serializable接口的作用:

1、将对象存储在介质中,以便下次使用时,可以快速重建一个副本;

2、便于数据传输,尤其是在远程调用的时候。

Serializable接口内容:

打开Serializable接口的源码,就会发现,这个接口其实是个空接口。

那么这个序列化操作,到底是由谁去实现了呢?

看一下接口的注释说明就知道,当我们让实体类实现Serializable接口时,其实是在告诉JVM此类可被序列化,可被默认的序列化机制序列化。

image-20230712133531900.png

Serializable接口的使用:

一个对象要实现序列化可以直接实现Serializable接口,并声明一个serialVersionUID即可,可以使用自动生成的或者手动指定如1L

@Slf4j
@Data
public class User implements Serializable {
​
    private static final long serialVersionUID = 6477564458830772334L;
    private int userId;
    private String userName;
​
    public User(int userId, String userName) {
        this.userId = userId;
        this.userName = userName;
    }
​
    public static void main(String[] args) {
        File file = new File("C:\Users\Administrator\Desktop\user.txt");
​
        //序列化
        User user = new User(1, "test");
        try {
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
            out.writeObject(user);
            out.close();
            log.info("====>", "序列化成功:");
        } catch (IOException e) {
            log.error("====>", "IOException:" + e);
            e.printStackTrace();
        }
​
        //反序列化
        try {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
            User user1 = (User) in.readObject();
            in.close();
            log.info("====>", "反序列化成功:"+user1);
        } catch (IOException e) {
            log.error("====>", "反序列化失败IOException:"+e);
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            log.error("====>", "反序列化失败ClassNotFoundException:"+e);
            e.printStackTrace();
        }
    }
​
}

对象序列化到文件后的样子:

image-20230712141253677.png