java-Bean拷贝工具类

Posted 阿拉的梦想

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java-Bean拷贝工具类相关的知识,希望对你有一定的参考价值。

java-Bean拷贝工具类

import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * ClassName: BeanCopyUtil
 * Description: Bean拷贝工具类
 *
 */
public class BeanCopyUtil {

    private BeanCopyUtil() {
    }

    /**
     * 将对象属性拷贝到目标类型的同名属性字段中
     * @param <T>
     * @param source
     * @param targetClazz
     * @return
     */
    public static <T> T copyProperties(Object source, Class<T> targetClazz) {

        T target = null;
        try {
            target = targetClazz.newInstance();
            BeanUtils.copyProperties(source, target);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return target;
    }

    /**
     * 将对象属性拷贝到目标类型的同名属性字段中
     * @param source
     * @param target
     * @return
     */
    public static <T> T copyProperties(Object source, T target) {
        BeanUtils.copyProperties(source, target);
        return target;
    }


    /**
     * 将list的对象拷贝到目标类型对象中
     * @param list
     * @param clazz
     * @return
     */
    public static <V, E> List<E> copy(Collection<V> list, Class<E> clazz) {
        List<E> result = new ArrayList<>(12);

        if (!CollectionUtils.isEmpty(list)) {
            for (V source : list) {
                E target = null;
                try {
                    target = (E) clazz.newInstance();
                    BeanUtils.copyProperties(source, target);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                result.add(target);
            }
        }

        return result;
    }

}

以上是关于java-Bean拷贝工具类的主要内容,如果未能解决你的问题,请参考以下文章

Android 逆向使用 DB Browser 查看并修改 SQLite 数据库 ( 从 Android 应用数据目录中拷贝数据库文件 | 使用 DB Browser 工具查看数据块文件 )(代码片段

elasticsearch代码片段,及工具类SearchEsUtil.java

solr分布式索引实战分片配置读取:工具类configUtil.java,读取配置代码片段,配置实例

java bean属性拷贝工具类比对(性能+功能)

危险!请马上替换代码中的BeanUtils!!!

JavaBean递归拷贝工具类Dozer