使用泛型来写BeanUtils.copyProperties

334 阅读1分钟
package com.wiki.utils;

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

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

public class CopyUtil {
    /**
     * 单体复制
     *
     * @param param
     * @param target
     * @param <T>
     * @return
     */

    public static <T> T copy(Object param, Class<T> target) {
        if (param == null) {
            return null;
        }
        T object = null;
        try {
            object = target.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        //复制
        BeanUtils.copyProperties(param, object);
        return object;
    }

    /**
     * 列表复制
     *
     * @param paramList
     * @param target
     * @param <T>
     * @return
     */
    public static <T> List<T> copyList(List paramList, Class<T> target) {
        List<T> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(paramList)) {
            for (Object c : paramList) {
                T obj = copy(c, target);
                list.add(obj);
            }
        }
        return list;
    }
}