Java DO到DTO转换工具类和BeanUtils.copyProperties()

项目中需要使用对象(DO)属性赋值给包含其属性子集的对象(DTO)或者显示层对象(VO)。

这种场景下需要大量调用get set方法,当属性较多时代码量较大而且非常繁琐。

因此采用反射机制,对此类场景进行简单封装。

import java.lang.reflect.Field;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 对象source私有属性复制给destination对象的同名私有属性工具
 * 注意:只支持属性名完全相同的属性复制,支持忽略一些属性,其他需要手动get set
 * @author 明明如月 w1251314@sohu.com
 */
public class PropertyUtils {

    /**
     * 将source对象的属性填充到destination对象对应属性中
     * @param source 原始对象
     * @param destination 目标对象
     */
    public static <S,D> void copyProperties(S source, D destination)  {
        Class clsDestination;
        try {
            clsDestination = Class.forName(destination.getClass().getName());

        Class clsSource = Class.forName(source.getClass().getName());

        Field[] declaredFields = clsDestination.getDeclaredFields();

        for (Field field : declaredFields){
            field.setAccessible(true);
            String fieldName = field.getName();
            try{
                //跳过serialVersionUID
                if("serialVersionUID".equals(fieldName)){
                    continue;
                }
                Field sourceField = clsSource.getDeclaredField(fieldName);
                sourceField.setAccessible(true);
                field.set(destination,sourceField.get(source));

            }catch (NoSuchFieldException e){
               // continue;
            }
        }
        } catch (Exception e) {
           throw new RuntimeException("PropertyUtils 属性转换错误");
        }

    }

    /**
     * 将source对象的属性填充到destination对象对应属性中
     * @param source 原始对象
     * @param destination 目标对象
     * @param ignoreProperties 不转换的属性
     */
    public static  <S,D> void copyProperties(S source, D destination,String... ignoreProperties)  {
        Class clsDestination ;
        try {
            clsDestination = Class.forName(destination.getClass().getName());

            Class clsSource = Class.forName(source.getClass().getName());

            Field[] declaredFields = clsDestination.getDeclaredFields();

            for (Field field : declaredFields){

                String fieldName = field.getName();

                Set<String> collect = Stream.of(ignoreProperties).collect(Collectors.toSet());
                //跳过serialVersionUID
                collect.add("serialVersionUID");

                if(collect.contains(fieldName)){
                    continue;
                }
                try{
                    field.setAccessible(true);
                    Field sourceField = clsSource.getDeclaredField(fieldName);
                    sourceField.setAccessible(true);
                    field.set(destination,sourceField.get(source));

                }catch (NoSuchFieldException e){
                    // 没有对应属性跳过;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("PropertyUtils 属性转换错误");
        }

    }



}

 

 

对于那些不重复的属性赋值,直接调用少量set方法即可。

 

 

 

不过最近发现Spring的提供了对应方法

在org.springframework.beans.BeanUtils类中有静态方法可以实现同名属性拷贝。

 

/**
 * Copy the property values of the given source bean into the target bean.
 * <p>Note: The source and target classes do not have to match or even be derived
 * from each other, as long as the properties match. Any bean properties that the
 * source bean exposes but the target bean does not will silently be ignored.
 * <p>This is just a convenience method. For more complex transfer needs,
 * consider using a full BeanWrapper.
 * @param source the source bean
 * @param target the target bean
 * @throws BeansException if the copying failed
 * @see BeanWrapper
 */
public static void copyProperties(Object source, Object target) throws BeansException {
   copyProperties(source, target, null, (String[]) null);
}

Note部分提到source和target类不必所有属性都匹配,而且不需要有继承关系。

另外值得注意的是

 

/**
 * Copy the property values of the given source bean into the given target bean,
 * ignoring the given "ignoreProperties".
 * <p>Note: The source and target classes do not have to match or even be derived
 * from each other, as long as the properties match. Any bean properties that the
 * source bean exposes but the target bean does not will silently be ignored.
 * <p>This is just a convenience method. For more complex transfer needs,
 * consider using a full BeanWrapper.
 * @param source the source bean
 * @param target the target bean
 * @param ignoreProperties array of property names to ignore
 * @throws BeansException if the copying failed
 * @see BeanWrapper
 */
public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException {
   copyProperties(source, target, null, ignoreProperties);
}

重载的此方法可以添加String类型的属性,这些属性在copy时将被忽略,非常实用。

 

受该方法启发,我们自己写的同名属性复制类也可以添加如此方法。

 

不过强烈不建议用属性拷贝工具类,建议定义转换工具类,然后写转换方法。

转换容易造成遗漏,类型错误等等。

 

另外可以参见https://blog.csdn.net/w605283073/article/details/89163627  使用GenerateO2O插件可以节省很大工作量。

 

 

如果觉得本文对你有帮助,欢迎点赞评论,欢迎关注我,我将努力创作更多更好的文章。

另外欢迎加入我的知识星球,知识星球ID:15165241 一起交流学习。

https://t.zsxq.com/Z3bAiea  申请时标注来自CSDN。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明明如月学长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值