序列化实现对象的拷贝

发布时间 2023-04-18 21:35:37作者: HexThinking

提到拷贝,大家第一时间想到的可能都是克隆模式的深克隆,因为这个模式在面试中出现的机率非常高,同时实现的方式也比较容易:对象的类实现Cloneable接口并且重写clone()方法即可。但是在实际情况中克隆模式有时候其实并不适合用来拷贝对象,因为如果有很多的实体类都需要拷贝,这个时候难道把这些实体类全都实现克隆模式?这是不提倡的,这个时候可以使用序列化方式来实现对象的拷贝。

package org.utils;

import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;

import java.io.*;

/**
 * 通过序列化方式实现clone
 * copyFrom需要实现Serializable
 */
public class CloneUtil {

    @SneakyThrows
    public static <T extends Serializable> T clone(T copyFrom) {
        T cloneObj = null;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(copyFrom);
        objectOutputStream.close();

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        cloneObj = (T) objectInputStream.readObject();
        objectInputStream.close();

        return cloneObj;
    }

    public static void main(String[] args) {
        User user = new User();
        user.setAge(30);
        user.setName("李四");
        User cloneUser = CloneUtil.clone(user);
        System.out.println(cloneUser.toString());
    }

    @Getter
    @Setter
    public static class User implements Serializable {
        {
            name = "张三";
            age = 20;
            location = "xxx";
        }

        private String name;
        private Integer age;
        private String location;

        @Override
        public String toString() {
            return "name:" + name + ",age:" + age + ",location:" + location;
        }

    }
}