张晓波
2023-09-19 164694c47c35d6654df69b533e8dbf8b5423efc5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.thhy.general.utils;
 
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.util.SerializationUtils;
 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
 
/**
 * @Author: zhang_xiao_bo
 * @Date: 2022/3/22 15:50
 * @description: 用于VO,DTO之间的拷贝
 */
public class DeepCopyUtils {
 
    /**
     * 默认采用SerializationUtils 需要bean 实现序列化 平均耗时10.1ms
     * @param source
     * @param target
     */
    public static void copy(Object source, Object target) {
        copySerialize(source,target);
    }
 
    /**
     * 采用手动io流序列化 ,需要bean 实现序列化 平均耗时9.8
     * @param source
     * @param target
     */
    public static void copyIo(Object source, Object target)  {
        try{
            //1、采用手动io流序列化 ,需要bean 实现序列化 平均耗时9.8
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(source);
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            Object temp = ois.readObject();
 
            //通过临时对象,将属性值,赋给b
            BeanUtils.copyProperties(temp,target);
        }catch (Exception e){
            e.printStackTrace();
        }
 
    }
 
    /**
     * 使用工具序列化SerializationUtils 需要bean 实现序列化 平均耗时10.1
     * @param source
     * @param target
     */
    public static void copySerialize(Object source, Object target)  {
        //2、使用工具序列化SerializationUtils 需要bean 实现序列化 平均耗时10.1
        Object temp = SerializationUtils.deserialize(SerializationUtils.serialize(source));
 
        //通过临时对象,将属性值,赋给b
        BeanUtils.copyProperties(temp,target);
    }
 
    /**
     * 依赖json包,bean无需实现序列化 平均耗时98.8
     * @param source
     * @param target
     */
    public static void copyJson(Object source, Object target)  {
        //3、下面转json得形式,依赖json包(反射原理) 依赖json包,bean无需实现序列化 平均耗时98.8
        Object temp = JSON.parseObject(JSON.toJSONString(source), source.getClass());
 
        //通过临时对象,将属性值,赋给b
        BeanUtils.copyProperties(temp,target);
    }
 
}