1. 程式人生 > 其它 >兩個實體類間的轉換

兩個實體類間的轉換

package com.lrhealth.mappingintegration.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author ppq
*/
@Slf4j
public class BeanHelper {

public static <T> T copyProperties(Object source, Class<T> target){
try {
T t = target.newInstance();
BeanUtils.copyProperties(source, t);
return t;
} catch (Exception e) {
log.error("【資料轉換】資料轉換出錯,目標物件{}建構函式異常", target.getName(), e);
return null;
}
}

public static <T> List<T> copyWithCollection(List<?> sourceList, Class<T> target){
try {
return sourceList.stream().map(s -> copyProperties(s, target)).collect(Collectors.toList());
} catch (Exception e) {
log.error("【資料轉換】資料轉換出錯,目標物件{}建構函式異常", target.getName(), e);
return null;
}
}

public static <T> Set<T> copyWithCollection(Set<?> sourceList, Class<T> target){
try {
return sourceList.stream().map(s -> copyProperties(s, target)).collect(Collectors.toSet());
} catch (Exception e) {
log.error("【資料轉換】資料轉換出錯,目標物件{}建構函式異常", target.getName(), e);
return null;
}
}
}