BeanHelp.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package com.usky.utils;
  2. import com.alibaba.fastjson.JSONObject;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.beans.BeanUtils;
  5. import java.util.List;
  6. import java.util.Set;
  7. import java.util.stream.Collectors;
  8. /**
  9. * @author laowo
  10. * @version v1.0
  11. * @date 2020/3/9 12:49
  12. * @description TODO
  13. **/
  14. @Slf4j
  15. public class BeanHelp {
  16. public static <T> T copyProperties(Object source, Class<T> target){
  17. try {
  18. T t = target.newInstance();
  19. BeanUtils.copyProperties(source, t);
  20. return t;
  21. } catch (Exception e) {
  22. log.error("【数据转换】数据转换出错,目标对象{}构造函数异常", target.getName(), e);
  23. //logger.error();
  24. // throw new LyException(ExceptionEnum.DATA_TRANSFER_ERROR);
  25. }
  26. return null;
  27. }
  28. public static <T> List<T> copyWithCollection(List<?> sourceList, Class<T> target){
  29. try {
  30. return sourceList.stream().map(s -> copyProperties(s, target)).collect(Collectors.toList());
  31. } catch (Exception e) {
  32. log.error("【数据转换】数据转换出错,目标对象{}构造函数异常", target.getName(), e);
  33. // throw new LyException(ExceptionEnum.DATA_TRANSFER_ERROR);
  34. }
  35. return null;
  36. }
  37. public static <T> Set<T> copyWithCollection(Set<?> sourceList, Class<T> target){
  38. try {
  39. return sourceList.stream().map(s -> copyProperties(s, target)).collect(Collectors.toSet());
  40. } catch (Exception e) {
  41. }
  42. return null;
  43. }
  44. /**
  45. * JSON字符串转对象
  46. * @param jsonStr
  47. * @param clazz
  48. * @return
  49. */
  50. public static <T> T jsonStrToObject(String jsonStr, Class<T> clazz){
  51. return JSONObject.parseObject(jsonStr, clazz);
  52. }
  53. /**
  54. * JSON字符串转List
  55. * @param type
  56. * @param listString
  57. * @return
  58. */
  59. public static <T> List<T> listStringToOjectList(String listString,Class<T> type){
  60. return JSONObject.parseArray(listString, type);
  61. }
  62. }