飞道的博客

数据对象转换工具

411人阅读  评论(0)

  
  1. /**
  2. * 数据对象转换工具
  3. */
  4. public class ConvertUtils {
  5. private static Logger logger = LoggerFactory.getLogger(ConvertUtils.class);
  6. /**
  7. * 转化出新对象
  8. * @param source 源对象
  9. * @param target 目标对象
  10. * @param <T>
  11. * @return
  12. */
  13. public static <T> T sourceToTarget(Object source, Class<T> target){
  14. if(source == null){
  15. return null;
  16. }
  17. T targetObject = null;
  18. try {
  19. targetObject = target.newInstance();
  20. BeanUtils.copyProperties(source, targetObject);
  21. } catch (Exception e) {
  22. logger.error( "convert error ", e);
  23. }
  24. return targetObject;
  25. }
  26. /**
  27. * 转化出新对象集合
  28. * @param sourceList 源对象集合
  29. * @param target 目标对象
  30. * @param <T> 新对象集合
  31. * @return
  32. */
  33. public static <T> List<T> sourceToTarget(Collection<?> sourceList, Class<T> target){
  34. if(sourceList == null){
  35. return null;
  36. }
  37. List targetList = new ArrayList<>(sourceList.size());
  38. try {
  39. for(Object source : sourceList){
  40. T targetObject = target.newInstance();
  41. BeanUtils.copyProperties(source, targetObject);
  42. targetList.add(targetObject);
  43. }
  44. } catch (Exception e){
  45. logger.error( "convert error ", e);
  46. }
  47. return targetList;
  48. }
  49. }

 


转载:https://blog.csdn.net/qq_42217906/article/details/104415317
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场