Bean 克隆小工具

记录一个克隆小工具,在需要的时候可以直接拿来使用

1、项目结构

在这里插入图片描述

2、项目依赖

首先新建一个SpringBoot项目,然后引入相应依赖

<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.4</version>
        </dependency>

3、BeanConvertUtils

package com.example.commontest.utils;

import lombok.Getter;
import lombok.Setter;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtilsBean;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.cglib.core.Converter;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Description: TODO
 * @Author:
 * @Date: 2023-4-27
 **/
public class BeanConvertUtils {

    private static Logger logger = LoggerFactory.getLogger(BeanConvertUtils.class);


    /**
     * 对象拷贝
     *
     * @param dest   目标对象
     * @param source 源对象
     * @return T1
     **/
    public static <T1, T2> T1 convertObject(T1 dest, T2 source) throws Exception {
        convert(dest, source);
        return dest;
    }

    /**
     * 对象拷贝
     *
     * @param dest   目标对象
     * @param source 源对象
     * @return void
     * @throws Exception
     */
    public static <T1, T2> void convert(T1 dest, T2 source) throws Exception {
        convert(dest, source, new DefaultConvert());
    }

    /**
     * 对象拷贝
     *
     * @param dest   目标对象
     * @param source 源对象
     * @return void
     * @throws Exception
     */
    public static <T1, T2> void convert(T1 dest, T2 source, Feature... features) throws Exception {
        convert(dest, source, new FeatureConverter(features));
    }

    public static <T1, T2> void convert(T1 dest, T2 source, Converter converter) throws Exception {
        if (null == dest || null == source) {
            return;
        }
        try {
            BeanCopier copier = BeanCopier.create(source.getClass(), dest.getClass(), converter != null);
            copier.copy(source, dest, converter);
        } catch (Exception e) {
            logger.error("", e);
            throw new Exception("系统异常");
        }
    }

    /**
     * 批量转换
     *
     * @param data
     * @param clazz
     * @return List<T2>
     * @throws Exception
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static <T2, T1> List<T2> convertList(List<T1> data, Class<T2> clazz) throws Exception {
        return convertList(data, clazz, new DefaultConvert());
    }


    /**
     * 批量转换
     *
     * @param data
     * @param clazz
     * @param converter
     * @return List<T2>
     * @throws Exception
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static <T2, T1> List<T2> convertList(List<T1> data, Class<T2> clazz, Converter converter) throws Exception {
        if (data == null) {
            return null;
        }

        List<T2> t2 = new ArrayList<T2>();
        if (null != data && data.size() > 0) {
            BeanCopier copier = BeanCopier.create(data.get(0).getClass(), clazz, converter != null);
            for (T1 t1 : data) {
                T2 tmp2;
                try {
                    tmp2 = clazz.getDeclaredConstructor().newInstance();
                } catch (Exception e) {
                    throw new Exception("系统异常");
                }
                copier.copy(t1, tmp2, converter);
                t2.add(tmp2);
            }
        }
        return t2;
    }

    static class DefaultConvert implements Converter {

        @SuppressWarnings("rawtypes")
        @Override
        public Object convert(Object value, Class target, Object context) {
            if (value instanceof Integer) {
                return Integer.valueOf(NumberUtils.toInt(value.toString()));
            } else if (value instanceof Float) {
                return Float.valueOf(NumberUtils.toFloat(value.toString()));
            } else if (value instanceof Double) {
                return Double.valueOf(NumberUtils.toDouble(value.toString()));
            } else if (value instanceof Short) {
                return Short.valueOf(NumberUtils.toShort(value.toString()));
            } else if (value instanceof BigDecimal) {
                return (BigDecimal) value;
            }
            return value;
        }
    }

    @Getter
    @Setter
    static class FeatureConverter implements Converter {

        private Feature[] features;

        private Set<Feature> featureSet;

        private ConvertUtilsBean convertUtils;

        public FeatureConverter(Feature[] features) {
            this.features = features;
            this.featureSet = new HashSet<>();
            if (null != features && features.length > 0) {
                featureSet.addAll(Arrays.asList(features));
            }
            this.convertUtils = BeanUtilsBean.getInstance().getConvertUtils();
            this.convertUtils.register(false, true, 0);
        }

        @SuppressWarnings("rawtypes")
        @Override
        public Object convert(Object value, Class target, Object context) {
            if (value instanceof String) {
                String str = String.valueOf(value);
                if (featureSet.contains(Feature.IgnoreBlank) && StringUtils.isBlank(str)) {
                    return null;
                }
            } else if (value instanceof Collection) {
                if (featureSet.contains(Feature.IgnoreEmpty) && ((Collection) value).isEmpty()) {
                    return null;
                }
            }
            return convert(value, target);
        }

        @SuppressWarnings("rawtypes")
        private Object convert(Object value, Class target) {
            return convertUtils.convert(value, target);
        }

    }

    public enum Feature {

        /**
         * 忽略空白字符串
         */
        IgnoreBlank,

        /**
         * 忽略空集合
         */
        IgnoreEmpty

    }

}

4、新建实体


@Data
public class OrderDTO {
    private String orderId;

    private String merchantId;

    private Integer amount;

    private String merchantName;

    private String companyCode;

    private String financeArea;
}



@Data
public class OrderBO {
    private String orderId;

    private String merchantId;

    private Integer amount;

    private String merchantName;

    private String companyCode;

    private String financeArea;

}

5、测试类及演示效果

public class BeanCopyTest {
    public static void main(String[] args) throws Exception {
        //创建dto
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setOrderId("10086");
        orderDTO.setMerchantId("11111");
        orderDTO.setMerchantName("测试商户");
        orderDTO.setCompanyCode("22222");
        orderDTO.setFinanceArea("33333");
        orderDTO.setAmount(10000);

        //bean copy
        OrderBO orderBO = new OrderBO();
        BeanConvertUtils.convert(orderBO,orderDTO);
        System.out.println(orderBO);

        System.out.println("----下面是集合克隆");
        OrderDTO orderDTO2 = new OrderDTO();
        BeanConvertUtils.convert(orderDTO2,orderDTO);
        orderDTO2.setMerchantName("测试商户2");
        List<OrderDTO> orderDTOS = Arrays.asList(orderDTO, orderDTO2);
        List<OrderBO> orderBOS = BeanConvertUtils.convertList(orderDTOS, OrderBO.class);
        System.out.println(orderBOS);
    }
}

演示效果
在这里插入图片描述

好的,就到这里了,有需要的朋友可以自取。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值