ReflectUtils.java 1.8 KB

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