属性转换工具

直接上代码

package com.lishikuan.myproject.utils;

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

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

/**
 * @Author: 李世宽
 * @Email: [email protected]
 * @Date: 2020/3/8 21:51
 */
public class BaseConvertUtil {

    private static Logger logger = LoggerFactory.getLogger(BaseConvertUtil.class);


    public static  T BeanConvert(Object source, Class target) {
        T targetObject = null;
        try {
            if (source == null) {
                return null;
            }
            targetObject = target.newInstance();
            BeanUtils.copyProperties(source, targetObject);
            return targetObject;
        } catch (Exception e) {
            logger.error(String.format("类型转换异常[%s] to [%s]", source.getClass(), target));
        }
        return targetObject;
    }


    public static  List BeanListConvert(List source, Class target) {
        try {
            if (source == null) {
                return null;
            }
            List targetList = new ArrayList<>();
            for (S s : source) {
                targetList.add(BeanConvert(s, target));
            }
            return targetList;
        } catch (Exception e) {
            logger.error(String.format("类型转换异常[%s] to [%s]", source.getClass(), target));
        }
        return null;
    }
}

你可能感兴趣的:(属性转换工具)