适用于VO到DO的复制转换
只会复制字段属性相同的内容 深度复制 必须实现Serializable
转载请注明出处
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName BeanCoveredUtils
* @Description
* @Author tianshuai
* @Date 2018/7/6 14:11
* @Version 1.0
**/
public class BeanCoveredUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(BeanCoveredUtils.class);
/**
* 对象属性复制
*
* @param source
* @param targetClass
* @param <T>
* @return
*/
public static <T> T beanCovered(Object source, Class<T> targetClass) {
if (source == null) {
return null;
}
T target = null;
try {
target = targetClass.newInstance();
} catch (Exception e) {
LOGGER.error("beanCovered error");
}
BeanUtils.copyProperties(source, target);
if(source instanceof Serializable) {
target = JSONArray.parseObject(JSONArray.toJSONString(source),targetClass);
}
return target;
}
/**
* 集合属性复制
*
* @param sourceList
* @param targetClass
* @param <T>
* @return
*/
public static <T> List<T> listCovered(List sourceList, Class<T> targetClass) {
ArrayList<T> targetList = new ArrayList();
if (CollectionUtils.isEmpty(sourceList)) {
return targetList;
}
for (Object source : sourceList) {
if (source != null) {
T target = null;
try {
target = targetClass.newInstance();
} catch (Exception e) {
LOGGER.error("listCovered error");
}
BeanUtils.copyProperties(source, target);
if(source instanceof Serializable) {
target = JSONArray.parseObject(JSONArray.toJSONString(source),targetClass);
}
targetList.add(target);
}
}
return targetList;
}
}