具体工具类
import org.springframework.cglib.beans.BeanCopier;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
/**
* @author admin
*/
public class BeanCopierUtil {
private BeanCopierUtil (){}
/**
* 缓存 BeanCopier,避免频繁创建 BeanCopier
*/
private static Map<String, BeanCopier> beanCopierMap = new ConcurrentHashMap<>();
/**
* 初始化 BeanCopier
* @param source
* @param target
* @return
*/
private static BeanCopier initCopier(Class source, Class target) {
BeanCopier beanCopier = BeanCopier.create(source, target, false);
beanCopierMap.put(source.getName() + "_" + target.getName(), beanCopier);
return beanCopier;
}
/**
* 获取BeanCopier
* @param source
* @param target
* @return
*/
private static BeanCopier getBeanCopier(Class source, Class target) {
BeanCopier beanCopier = beanCopierMap.get(source.getClass().getName() + "_" + target.getName());
if (beanCopier != null) {
return beanCopier;
}
return initCopier(source, target);
}
public static void copy(Object from, Object to) {
BeanCopier copier = getBeanCopier(from.getClass(), to.getClass());
copier.copy(from, to, null);
}
public static <S,T> T copy(S from, Supplier<T> to,Class<T> clazz, BeanCopierUtilCallBack<S, T> callBack) {
BeanCopier copier = getBeanCopier(from.getClass(), clazz);
T t = to.get();
copier.copy(from, t, null);
if (callBack != null) {
// 回调
callBack.callBack(from, t);
}
return t;
}
public static <T> T copy(Object from, Supplier<T> to,Class<T> clazz) {
return copy(from,to,clazz,null);
}
/**
* 集合数据的拷贝
* @param sources: 数据源类
* @param target: 目标类::new(eg: UserVO::new)
* @return
*/
public static <S, T> List<T> copyListProperties(List<S> sources, Supplier<T> target) {
return copyListProperties(sources, target, null);
}
/**
* 带回调函数的集合数据的拷贝(可自定义字段拷贝规则)
* @param sources: 数据源类
* @param target: 目标类::new(eg: UserVO::new)
* @param callBack: 回调函数
* @return
*/
public static <S, T> List<T> copyListProperties(List<S> sources, Supplier<T> target, BeanCopierUtilCallBack<S, T> callBack) {
List<T> list = new ArrayList<>(sources.size());
for (S source : sources) {
T t = target.get();
copy(source, t);
list.add(t);
if (callBack != null) {
// 回调
callBack.callBack(source, t);
}
}
return list;
}
}
BeanCopierUtilCallBack
@FunctionalInterface
public interface BeanCopierUtilCallBack<S, T> {
/**
* 默认回调方法
* @param s
* @param t
*/
void callBack(S t, T s);
}
集合拷贝参考用法
LocalDateTime now = LocalDateTime.now();
List<B> list = BeanCopierUtil.copyListProperties(aList, B::new
, (a, b) -> {
b.setCreateTime(now);
b.setModifyTime(now);
b.setBatchId(snowflakeNextId);
});
- 本文链接: http://maltose.top/archives/dui-xiang-shu-xing-kao-bei--shen-kao-bei--gong-ju-lei
- 版权声明: 本博客所有文章除特别声明外,均采用CC BY-NC-SA 3.0 许可协议。转载请注明出处!