java复制bean

一、瞎扯

      对于bean的复制(obj1-->obj2),常见的有两个工具类,一个是org.springframework.beans.BeanUtils,一个是org.apache.commons.beanutils.BeanUtils。。

      至于两者的一些区别,请看博客:

            https://www.cnblogs.com/dongfangshenhua/p/7099970.html

            https://blog.csdn.net/langqiao123/article/details/72961383/

      官方文档:

            https://docs.spring.io/spring-framework/docs/1.1.1/api/org/springframework/beans/BeanUtils.html

二、我的案例

      基于org.springframework.beans.BeanUtils对于对象复制的支持,我写了个工具类,简单的封装了一下。。

      1、项目结构:

      2、pom文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>me.ele</groupId>
    <artifactId>beanUtilsDemo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>

    </dependencies>

</project>

      3、代码:

package me.ele;

import org.springframework.beans.BeanUtils;

import java.beans.PropertyDescriptor;
import java.util.*;

/**
 * @author LZJ
 * @create 2018-10-11 19:47
 **/
public class BeanCopyUtils {

    /**
     * 将一个collection<bean> 根据某一class 进行copy
     *
     * @param froms
     * @param toClazz
     * @param <T>
     * @return
     */
    public static <T> Collection<T> copy(Collection<?> froms, Class<T> toClazz) {
        if (froms == null)
            return null;
        Collection<T> toList;
        try {
            toList = froms.getClass().newInstance();
            if (froms instanceof List) {
                toList = new ArrayList<T>();
            } else if (froms instanceof Set) {
                toList = new HashSet<T>();
            }
            for (Object obj : froms) {
                T to = copy(obj, toClazz);
                toList.add(to);
            }
        } catch (Exception e) {
            throw new RuntimeException("copy exception", e);
        }
        return toList;
    }

    /**
     * 将一个bean[] 根据某一class 进行copy
     *
     * @param froms   List<Object>
     * @param toClazz 某一class
     * @param <T>
     * @return List<lass的实例>
     */
    public static <T> Collection<T> copy(Object[] froms, Class<T> toClazz) {
        if (froms == null) {
            return null;
        }
        List<T> toList = new ArrayList<>();
        for (Object obj : froms) {
            T to = copy(obj, toClazz);
            toList.add(to);
        }
        return toList;
    }

    /**
     * 将一个bean 根据某一class 进行copy
     *
     * @param from    Object
     * @param toClazz 某一class的名称
     * @param <T>
     * @return class的实例
     */
    public static <T> T copy(Object from, Class<T> toClazz) {
        if (from == null) {
            return null;
        }
        T to;
        try {
            to = toClazz.newInstance();
            copy(to, from);
        } catch (Exception e) {
            throw new RuntimeException("copy exception", e);
        }
        return to;
    }

    /**
     * 将一个bean 直接复制给另一个 bean
     *
     * @param from 初始bean
     * @param to   目标bean
     */
    public static void copy(Object from, Object to) {
        if (from == null) {
            return;
        }
        try {
            BeanUtils.copyProperties(from, to);
        } catch (Exception e) {
            throw new RuntimeException("copy exception", e);
        }
    }

    /**
     * 将一个map对象 ,对象中key为属性名,value为属性值,根据某一class进行copy
     *
     * @param toClazz
     * @param from
     * @param <T>
     * @return
     */
    public static <T> T copy(Class<T> toClazz, Map<String, Object> from) {
        if (from == null || from.isEmpty()) {
            return null;
        }
        T to;
        try {
            to = toClazz.newInstance();
            copy(to, from);
        } catch (Exception e) {
            throw new RuntimeException("copy exception", e);
        }
        return to;
    }

    /**
     * 将一个map对象 ,对象中key为属性名,value为属性值 copy值某一object
     *
     * @param to
     * @param from
     */
    public static void copy(Object to, Map<String, Object> from) {
        if (from == null || from.isEmpty()) {
            return;
        }
        PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(to.getClass());
        from.forEach((String propertyName, Object value) -> {
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                if (propertyDescriptor.getName().equals(propertyName)
                        || propertyDescriptor.getName().toLowerCase().equals(propertyName.toLowerCase())) {
                    try {
                        propertyDescriptor.getWriteMethod().invoke(to, value);
                    } catch (Exception e) {
                        throw new RuntimeException("copy exception", e);
                    }
                }
            }
        });
    }
}

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值