package net.northking.cctp.testbug.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: puchao.ma
 * @date: 2021/10/9 10:31
 */
public class BeanHelper {

    /**
     * 日志
     */
    private final static Logger logger = LoggerFactory.getLogger(BeanHelper.class);

    public static <T> T copyProperties(Object source, Class<T> target) {
        try {
            T t = target.newInstance();
            BeanUtils.copyProperties(source, t);
            return t;
        } catch (Exception e) {
            logger.error("数据转换异常, 目标对象{}构造函数异常", target.getName(), e);
            return null;
        }
    }

    public static <T> List<T> copyWithCollection(List<?> sourceList, Class<T> target) {
        try {
            return sourceList.stream().map(s -> copyProperties(s, target)).collect(Collectors.toList());
        } catch (Exception e) {
            logger.error("数据转换异常, 目标对象{}构造函数异常", target.getName(), e);
            return null;
        }
    }
}
