ReflectUtils.java 1.9 KB

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