DozerUtils.java 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package com.poyee.common.utils.bean;
  2. import com.github.dozermapper.core.DozerBeanMapperBuilder;
  3. import com.github.dozermapper.core.Mapper;
  4. import java.util.ArrayList;
  5. import java.util.Collection;
  6. import java.util.List;
  7. public class DozerUtils {
  8. /**
  9. * commonMapper,如果没有传mapper过来,默认使用这个
  10. * dozer/dozer-mapping.xml 是相对resources目录的路径
  11. */
  12. public static Mapper mapper = DozerBeanMapperBuilder.create()
  13. .withMappingFiles("dozer/dozer-mapping.xml")
  14. .build();
  15. /**
  16. * 单个对象转换
  17. * 传入需要转换的对象,返回转换后的对象
  18. * 用法:CommonDozerUtil.map(dto,Destination.class)
  19. *
  20. * @param source 源对象
  21. * @param destinationClass
  22. * @param <T>
  23. * @return
  24. */
  25. public static <T> T map(Object source, Class<T> destinationClass) {
  26. if (source != null) {
  27. return mapper.map(source, destinationClass);
  28. }
  29. return null;
  30. }
  31. /**
  32. * list转换
  33. * 用法:CommonDozerUtil.mapList(list,Destination.class)
  34. *
  35. * @param sourceList
  36. * @param destinationClass
  37. * @param <T>
  38. * @return
  39. */
  40. public static <T> List<T> mapList(Collection<?> sourceList, Class<T> destinationClass) {
  41. List<T> destinationList = new ArrayList<>();
  42. if (sourceList != null && sourceList.size() > 0) {
  43. for (Object sourceObject : sourceList) {
  44. T destinationObject = map(sourceObject, destinationClass);
  45. destinationList.add(destinationObject);
  46. }
  47. }
  48. return destinationList;
  49. }
  50. /**
  51. * 将对象A的值拷贝到对象B中
  52. *
  53. * @param source 对象A
  54. * @param destinationObject 对象B
  55. */
  56. public static void copy(Object source, Object destinationObject) {
  57. mapper.map(source, destinationObject);
  58. }
  59. }