Commit a1c2069a authored by liaozan's avatar liaozan 🏀

BeanCopyUtils support property type convert

parent d210f6a0
......@@ -2,9 +2,14 @@ package com.schbrain.common.util;
import cn.hutool.core.lang.Singleton;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.google.common.base.Joiner;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeansException;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.cglib.core.Converter;
import org.springframework.core.convert.ConversionService;
import org.springframework.util.ClassUtils;
import java.util.ArrayList;
import java.util.List;
......@@ -19,6 +24,8 @@ public class BeanCopyUtils {
private static final Joiner CACHE_KEY_JOINER = Joiner.on("#");
private static final ConversionServiceConverter CONVERTER = new ConversionServiceConverter();
/**
* copy object list
*/
......@@ -47,17 +54,46 @@ public class BeanCopyUtils {
return null;
}
BeanCopier copier = getCopier(source.getClass(), target.getClass());
copier.copy(source, target, null);
copier.copy(source, target, CONVERTER);
return target;
}
private static BeanCopier getCopier(Class<?> sourceClass, Class<?> targetClass) {
String cacheKey = buildCacheKey(sourceClass, targetClass);
return Singleton.get(cacheKey, () -> BeanCopier.create(sourceClass, targetClass, false));
return Singleton.get(cacheKey, () -> BeanCopier.create(sourceClass, targetClass, true));
}
private static String buildCacheKey(Class<?> source, Class<?> target) {
return CACHE_KEY_JOINER.join(source.getName(), target.getName());
}
@SuppressWarnings("unchecked")
private static class ConversionServiceConverter implements Converter {
private ConversionService conversionService;
private ConversionServiceConverter() {
try {
this.conversionService = SpringUtil.getBean(ConversionService.class);
} catch (BeansException e) {
this.conversionService = null;
}
}
@Override
public Object convert(Object value, Class targetType, Object context) {
if (value == null) {
return null;
}
if (ClassUtils.isAssignableValue(targetType, value)) {
return value;
}
if (conversionService != null && conversionService.canConvert(value.getClass(), targetType)) {
return conversionService.convert(value, targetType);
}
return value;
}
}
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment