/**
-
@author : lssffy
-
@Description : 复制对象
-
@date : 2023/5/29 10:33
*/
@Slf4j
public class BeanCopy {public static T copy(Object source, Class target) {
if(target == null){
return null;
}
try {
T t = target.newInstance();
return copy(source,t);
}catch (Exception e){
log.error(“Failed to copy:{}” , e);
throw new BusinessException(CommonErrors.COPY_OBJ_FAIL,e);
}
}public static T copy(Object source, T target){
if(target == null || source == null){
return null;
}
BeanCopier copier = BeanCopier.create(source.getClass(), target.getClass(),true);
copier.copy(source, target, new Converter() {
@Override
public Object convert(Object obj, Class cls, Object context) {
if(obj == null){
return null;
}
/**
* source is String,target is Date
/
else if((obj instanceof String) && Date.class.isAssignableFrom(cls)){
return DateUtils.parseDate((String) obj);
}
/*
* source is Date, target is String
/
else if((obj instanceof Date) && String.class.isAssignableFrom(cls)){
return DateFormatUtils.format((Date) obj);
}
/*
* source is not String, target is String
/
else if(!(obj instanceof String) && String.class.isAssignableFrom(cls)) {
return String.valueOf(obj);
}
/*
* different custom objects, but with the same fields name
*/
else if(cls.toString().contains(“com.example”) && !cls.equals(obj.getClass())){
return copy(obj, cls);
}
return obj;
}
});
return target;
}/**
- if source、target is element to list,but both is object is not same as type。
- @param source
- @param target
- @param properties
*/
public static void copyProperties(Object source,Object target,String… properties){
BeanUtils.copyProperties(source,target,properties);
}
public static T copyProperties(Object source,Class cls,String… properties){
T target;
try {
target = cls.newInstance();
} catch (Exception e){
log.error(“Cannot copy properties:{}”, e);
throw new BusinessException(CommonErrors.INSTANCE_OBJ_FAIL,e);
}
return target;
}public static List copyList(List<?> source, Class cls){
if(source == null){
return null;
}
return source.stream().map(s->copy(s,cls)).collect(Collectors.toList());
}
}