import com.google.common.collect.Lists;
import org.modelmapper.AbstractConverter;
import org.modelmapper.Converter;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
/**
* 对象拷贝工具类
*
* @author YML
* @since 2022/06/22
*/
@SuppressWarnings("unused")
public class ModelMapperUtil {
private static final ModelMapper MODEL_MAPPER = new ModelMapper();
static {
Converter<String, LocalDateTime> toStringDate = new AbstractConverter<String, LocalDateTime>() {
@Override
protected LocalDateTime convert(String source) {
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
LocalDateTime dateTimeParked = LocalDateTime.parse(source, formatter);
return dateTimeParked;
}
};
MODEL_MAPPER.addConverter(toStringDate);
MODEL_MAPPER.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
}
/**
* 单个对象拷贝
*/
public static <D> D strictMap(Object source, Class<D> destinationType) {
return source == null ? null : MODEL_MAPPER.map(source, destinationType);
}
/**
* 数组对象拷贝
*/
@SuppressWarnings(value = "unchecked")
public static <D> List<D> strictMapList(Object source, Class<D> componentType) {
if (source == null) {
return null;
} else {
List<D> list = Lists.newArrayList();
List<Object> objectList = (List<Object>) source;
for (Object obj : objectList) {
list.add(MODEL_MAPPER.map(obj, componentType));
}
return list;
}
}
}
对象拷贝工具类
最新推荐文章于 2024-09-26 10:24:41 发布