使用Hutool实现深复制,非序列化

本文介绍了如何使用Hutool库来实现对象的深复制,避免使用序列化方法。通过递归复制的方式,分别展示了测试代码、BeanA和BeanB的实例,以及@DeepCopy注解的应用。
摘要由CSDN通过智能技术生成

思路

  • 递归复制

测试代码

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.ReflectUtil;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.*;

public class DeepCopyPropertiesTest {
   
    public static void main(String[] args) {
   
        List<BeanA> beanAList = CollUtil.newArrayList();
        for (int i = 0; i < 3; i++) {
   
            BeanA beanA = new BeanA("beanA" + i, i);
            beanAList.add(beanA);
        }
        BeanA beanA = new BeanA("beanAOutSideTheList", 30);
        Map<String, BeanA> map = new HashMap<>();
        map.put("aa", beanA);
        BeanB beanB = new BeanB("beanB", beanAList, beanA, map);
        BeanB copyBeanB = new BeanB();
        BeanUtil.deepCopyProperties(beanB, copyBeanB);
        Console.log(beanB.getBeanA() == copyBeanB.getBeanA());
        Console.log(beanB.getBeanAList().get(1) == copyBeanB.getBeanAList().get(1));
        Console.log(beanB.getMap().get("aa") == copyBeanB.getMap().get("aa"));
        Console.log(beanB);
        Console.log(copyBeanB);
    }
}

BeanA

public class BeanA {
   
    private String name = "beanA";
    private int age = 20;

    public BeanA() {
   
    }

    public BeanA(String name, int age) {
   
        this.name = name;
        this.age = age;
    }

    public String getName() {
   
        return name;
    }

    public void setName(String name) {
   
        this.name =
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值