BeanUtil.java 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package com.diagbot.util;
  2. import org.springframework.beans.BeanUtils;
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.List;
  6. /**
  7. * @Description: 对象转换工具类
  8. * @author: gaodm
  9. * @time: 2018/12/14 14:21
  10. */
  11. public class BeanUtil {
  12. /**
  13. * 把一个对象的属性值复制给另外一个对象的属性值
  14. *
  15. * @param source 源对象,被转换的对象
  16. * @param target 目标对象,即转换后对象
  17. */
  18. public static void copyProperties(Object source, Object target) {
  19. BeanUtils.copyProperties(source, target);
  20. }
  21. /**
  22. * 复制集合
  23. *
  24. * @param <E>
  25. * @param source 转换前的列表
  26. * @param destinationClass 转换后列表类
  27. * @return 转换后列表
  28. */
  29. public static <E> List<E> listCopyTo(List<?> source, Class<E> destinationClass) {
  30. try {
  31. if (source.size() == 0) {
  32. return Collections.emptyList();
  33. }
  34. List<E> res = new ArrayList<E>(source.size());
  35. for (Object o : source) {
  36. E e = destinationClass.newInstance();
  37. BeanUtils.copyProperties(o, e);
  38. res.add(e);
  39. }
  40. return res;
  41. } catch (IllegalAccessException ex) {
  42. throw new RuntimeException(ex);
  43. } catch (InstantiationException ex) {
  44. throw new RuntimeException(ex);
  45. }
  46. }
  47. }