BeanTransferUtils.java 1.44 KB
package org.nafmii.common.param;

import com.github.pagehelper.Page;
import org.springframework.util.CollectionUtils;

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

/**
 * @author by zhangbr
 * @date 2020/3/26.
 */
public class BeanTransferUtils {

    public static <T> T transfer(Object text, Class<T> clazz) {
        T t;
        try {
            t = clazz.newInstance();
            if (text != null){
                org.springframework.beans.BeanUtils.copyProperties(text, t);
            }
            return t;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> transferList(List<?> list, Class<T> clazz) {
        if(CollectionUtils.isEmpty(list)){
            return Collections.emptyList();
        }
        List<T> result =new ArrayList<>();
        for(Object each : list) {
            result.add(transfer(each,clazz));
        }
        return  result;
    }
    public static <T> PageResult<T> toPagedResult(List<?> list, Class<T> clazz) {
        PageResult<T> result = new PageResult();
        if (list instanceof Page) {
            Page page = (Page)list;
            result.setTotal(page.getTotal());
        } else if (list != null) {
            result.setTotal((long)list.size());
        }

        if (list != null && !list.isEmpty()) {
            result.setList(transferList(list, clazz));
        }

        return result;
    }
}