前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java DO到DTO转换工具类和BeanUtils.copyProperties()

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

作者头像
明明如月学长
发布2021-08-27 16:21:44
1.3K0
发布2021-08-27 16:21:44
举报
文章被收录于专栏:明明如月的技术专栏

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

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

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

代码语言:javascript
复制
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  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   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 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类中有静态方法可以实现同名属性拷贝。

代码语言:javascript
复制
/**
 * Copy the property values of the given source bean into the target bean.
 * 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.
 * 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类不必所有属性都匹配,而且不需要有继承关系。

另外值得注意的是

代码语言:javascript
复制
/**
 * Copy the property values of the given source bean into the given target bean,
 * ignoring the given "ignoreProperties".
 * 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.
 * 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。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018/05/18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档