BeanUtils.copyProperties转换工具类,解决list转换

package com.flightroutes.flight.bill.anewbill.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
public class BeanCopyTool {

public static  T convertCopyBean(Object source, Class clazz) {
    if (source == null) {
        return null;
    }
    try {
        T target = clazz.newInstance();
        BeanUtils.copyProperties(source, target);
        return target;
    } catch (Exception ex) {
        log.error("转换错误",ex);
    }
    return null;
}

public static  List convertCopyList(Collection oldList, Class clazz) {
    List newList = new ArrayList<>();
    if (oldList != null && !oldList.isEmpty()) {
        try {
            for (Object item : oldList) {
                T newObj = clazz.newInstance();
                BeanUtils.copyProperties(item, newObj);
                newList.add(newObj);
            }
        } catch (Exception ex) {
            log.error("转换错误",ex);
        }
    }
    return newList;
}

}

你可能感兴趣的:(java)