当前位置:   article > 正文

30.对象转换工具类_supplier targetsupplier

supplier targetsupplier
  1. import org.apache.commons.beanutils.BeanUtils;
  2. import java.lang.reflect.InvocationTargetException;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.function.Supplier;
  6. /**
  7. * 转换对象工具
  8. *
  9. * @author zj
  10. * @date 2022/06/14 17:12
  11. **/
  12. public class CustomBeanConvertUtils extends BeanUtils {
  13. public static <S, T> T convertTo(S source, Supplier<T> targetSupplier) throws InvocationTargetException, IllegalAccessException {
  14. return convertTo(source, targetSupplier, null);
  15. }
  16. /**
  17. * 转换对象
  18. *
  19. * @param source 源对象
  20. * @param targetSupplier 目标对象供应方
  21. * @param callBack 回调方法
  22. * @param <S> 源对象类型
  23. * @param <T> 目标对象类型
  24. * @return 目标对象
  25. */
  26. public static <S, T> T convertTo(S source, Supplier<T> targetSupplier, ConvertCallBack<S, T> callBack) throws InvocationTargetException, IllegalAccessException {
  27. if (null == source || null == targetSupplier) {
  28. return null;
  29. }
  30. T target = targetSupplier.get();
  31. copyProperties(source, target);
  32. if (callBack != null) {
  33. callBack.callBack(source, target);
  34. }
  35. return target;
  36. }
  37. public static <S, T> List<T> convertListTo(List<S> sources, Supplier<T> targetSupplier) throws InvocationTargetException, IllegalAccessException {
  38. return convertListTo(sources, targetSupplier, null);
  39. }
  40. /**
  41. * 转换对象
  42. *
  43. * @param sources 源对象list
  44. * @param targetSupplier 目标对象供应方
  45. * @param callBack 回调方法
  46. * @param <S> 源对象类型
  47. * @param <T> 目标对象类型
  48. * @return 目标对象list
  49. */
  50. public static <S, T> List<T> convertListTo(List<S> sources, Supplier<T> targetSupplier, ConvertCallBack<S, T> callBack) throws InvocationTargetException, IllegalAccessException {
  51. if (null == sources || null == targetSupplier) {
  52. return null;
  53. }
  54. List<T> list = new ArrayList<>(sources.size());
  55. for (S source : sources) {
  56. T target = targetSupplier.get();
  57. copyProperties(source, target);
  58. if (callBack != null) {
  59. callBack.callBack(source, target);
  60. }
  61. list.add(target);
  62. }
  63. return list;
  64. }
  65. /**
  66. * 回调接口
  67. *
  68. * @param <S> 源对象类型
  69. * @param <T> 目标对象类型
  70. */
  71. @FunctionalInterface
  72. public interface ConvertCallBack<S, T> {
  73. void callBack(S t, T s);
  74. }
  75. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/138541
推荐阅读
相关标签
  

闽ICP备14008679号