bean 拷贝 工具总结

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

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

/**
 * @Description: 领域模型转换工具类
 */
@Component
public class ConvertDomainUtils {

    /**
     * 通用bean拷贝排除属性
     */
    public static String[] IGNORE_PROPERTIES = new String[]{""};

    /**
     * @Description: DO VO 对象拷贝
     * @param:
     * @Return
     */
    public static <K, V> V convertDomainForBean(K source, Class<V> v, String[] ignoreProperties) {
        V target = null;
        try {
            target = v.newInstance();
            BeanUtils.copyProperties(source, target, ignoreProperties);
        } catch (InstantiationException ie) {
            ie.printStackTrace();
            return target;
        } catch (IllegalAccessException iae) {
            iae.printStackTrace();
            return target;
        }
        return target;
    }

    /**
     * @Description: DO VO 集合拷贝
     * @param: List<K>
     * @param: Class<V>
     * @param: String[] 排除属性
     * @Return: List<V>
     */
    public static <K, V> List<V> convertDomainForList(List<K> sourceList, Class<V> v, String[] ignoreProperties) {
        List<V> targetList = new ArrayList<V>();
        for (K source : sourceList) {
            targetList.add(convertDomainForBean(source, v, ignoreProperties));
        }
        return targetList;
    }

    /**
     * @Description: DO VO 分页集合拷贝
     * @param: Page<K>
     * @param: Class<V>
     * @param: String[] 排除属性
     * @Return: IPage<V>
     */
    public static <K, V> IPage<V> convertDomainForPage(IPage<K> sourcePage, Class<V> v, String[] ignoreProperties) {
        IPage<V> targetPage = new Page<V>(sourcePage.getCurrent(), sourcePage.getSize(), sourcePage.getTotal());
        targetPage.setRecords(convertDomainForList(sourcePage.getRecords(), v, ignoreProperties));
        return targetPage;
    }
}
 

猜你喜欢

转载自blog.csdn.net/qq_33715846/article/details/90203626