package com.zd.common.core.utils.bean;

import com.zd.common.core.exception.ServiceException;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;

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

/**
 * 集合对象转换工具
 */
public class TransferUtils {

    private TransferUtils() {
    }

    /**
     * List 之间的转换
     *
     * @param tList 源数据
     * @param clazz 目标对象类
     * @param <T>   原对象
     * @param <K>   目标对象
     * @return 集合
     */
    public static <T, K> List<K> transferList(Collection<T> tList, Class<K> clazz) {
        if (!CollectionUtils.isNotEmpty(tList)) {
            return Collections.emptyList();
        } else {
            List<K> kList = new ArrayList<>();
            for (T t : tList) {
                K tk;
                try {
                    tk = clazz.newInstance();
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new ServiceException(e.getMessage());
                }
                BeanUtils.copyProperties(t,tk);
                kList.add(tk);
            }
            return kList;
        }
    }

}
