ReflectUtils.java 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package com.ruoyi.common.utils.reflect;
  2. import cn.hutool.core.util.ReflectUtil;
  3. import cn.hutool.core.util.StrUtil;
  4. import java.lang.reflect.Method;
  5. import java.util.List;
  6. /**
  7. * 反射工具类. 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
  8. *
  9. * @author Lion Li
  10. */
  11. @SuppressWarnings("rawtypes")
  12. public class ReflectUtils extends ReflectUtil {
  13. private static final String SETTER_PREFIX = "set";
  14. private static final String GETTER_PREFIX = "get";
  15. /**
  16. * 调用Getter方法.
  17. * 支持多级,如:对象名.对象名.方法
  18. */
  19. @SuppressWarnings("unchecked")
  20. public static <E> E invokeGetter(Object obj, String propertyName) {
  21. Object object = obj;
  22. for (String name : StrUtil.split(propertyName, ".")) {
  23. String getterMethodName = GETTER_PREFIX + StrUtil.upperFirst(name);
  24. object = invoke(object, getterMethodName);
  25. }
  26. return (E) object;
  27. }
  28. /**
  29. * 调用Setter方法, 仅匹配方法名。
  30. * 支持多级,如:对象名.对象名.方法
  31. */
  32. public static <E> void invokeSetter(Object obj, String propertyName, E value) {
  33. Object object = obj;
  34. List<String> names = StrUtil.split(propertyName, ".");
  35. for (int i = 0; i < names.size(); i++) {
  36. if (i < names.size() - 1) {
  37. String getterMethodName = GETTER_PREFIX + StrUtil.upperFirst(names.get(i));
  38. object = invoke(object, getterMethodName);
  39. } else {
  40. String setterMethodName = SETTER_PREFIX + StrUtil.upperFirst(names.get(i));
  41. Method method = getMethodByName(object.getClass(), setterMethodName);
  42. invoke(object, method, value);
  43. }
  44. }
  45. }
  46. }