Java 深拷贝方法,可以拷贝集合

package a.b.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collections;
import java.util.List;

/**
 * @author liguoping
 * @since 2022/2/25 17:03
 */
@Slf4j
public class SerializationUtils {
    
    /**
     * 深拷贝
     *
     * @param src 原始数据
     * @param  泛型
     * @return 深拷贝数据
     */
    @SuppressWarnings("unchecked")
    public static  List deepCopy(List src) {
        ByteArrayOutputStream byteOut = null;
        ObjectOutputStream out = null;
        ByteArrayInputStream byteIn = null;
        ObjectInputStream in = null;
        try {
            byteOut = new ByteArrayOutputStream();
            out = new ObjectOutputStream(byteOut);
            out.writeObject(src);
            byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            in = new ObjectInputStream(byteIn);
            return (List) in.readObject();
        } catch (Exception ex) {
            log.error("深拷贝异常", ex);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(byteIn);
            IOUtils.closeQuietly(out);
            IOUtils.closeQuietly(byteOut);
        }
        return Collections.emptyList();
    }
}

你可能感兴趣的:(Java 深拷贝方法,可以拷贝集合)