BeanUtils.java 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package com.ruoyi.common.utils.bean;
  2. import java.lang.reflect.Method;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.regex.Matcher;
  6. import java.util.regex.Pattern;
  7. /**
  8. * Bean 工具类
  9. *
  10. * @author ruoyi
  11. */
  12. public class BeanUtils extends org.springframework.beans.BeanUtils
  13. {
  14. /** Bean方法名中属性名开始的下标 */
  15. private static final int BEAN_METHOD_PROP_INDEX = 3;
  16. /** * 匹配getter方法的正则表达式 */
  17. private static final Pattern GET_PATTERN = Pattern.compile("get(\\p{javaUpperCase}\\w*)");
  18. /** * 匹配setter方法的正则表达式 */
  19. private static final Pattern SET_PATTERN = Pattern.compile("set(\\p{javaUpperCase}\\w*)");
  20. /**
  21. * Bean属性复制工具方法。
  22. *
  23. * @param dest 目标对象
  24. * @param src 源对象
  25. */
  26. public static void copyBeanProp(Object dest, Object src)
  27. {
  28. try
  29. {
  30. copyProperties(src, dest);
  31. }
  32. catch (Exception e)
  33. {
  34. e.printStackTrace();
  35. }
  36. }
  37. /**
  38. * 获取对象的setter方法。
  39. *
  40. * @param obj 对象
  41. * @return 对象的setter方法列表
  42. */
  43. public static List<Method> getSetterMethods(Object obj)
  44. {
  45. // setter方法列表
  46. List<Method> setterMethods = new ArrayList<Method>();
  47. // 获取所有方法
  48. Method[] methods = obj.getClass().getMethods();
  49. // 查找setter方法
  50. for (Method method : methods)
  51. {
  52. Matcher m = SET_PATTERN.matcher(method.getName());
  53. if (m.matches() && (method.getParameterTypes().length == 1))
  54. {
  55. setterMethods.add(method);
  56. }
  57. }
  58. // 返回setter方法列表
  59. return setterMethods;
  60. }
  61. /**
  62. * 获取对象的getter方法。
  63. *
  64. * @param obj 对象
  65. * @return 对象的getter方法列表
  66. */
  67. public static List<Method> getGetterMethods(Object obj)
  68. {
  69. // getter方法列表
  70. List<Method> getterMethods = new ArrayList<Method>();
  71. // 获取所有方法
  72. Method[] methods = obj.getClass().getMethods();
  73. // 查找getter方法
  74. for (Method method : methods)
  75. {
  76. Matcher m = GET_PATTERN.matcher(method.getName());
  77. if (m.matches() && (method.getParameterTypes().length == 0))
  78. {
  79. getterMethods.add(method);
  80. }
  81. }
  82. // 返回getter方法列表
  83. return getterMethods;
  84. }
  85. /**
  86. * 检查Bean方法名中的属性名是否相等。<br>
  87. * 如getName()和setName()属性名一样,getName()和setAge()属性名不一样。
  88. *
  89. * @param m1 方法名1
  90. * @param m2 方法名2
  91. * @return 属性名一样返回true,否则返回false
  92. */
  93. public static boolean isMethodPropEquals(String m1, String m2)
  94. {
  95. return m1.substring(BEAN_METHOD_PROP_INDEX).equals(m2.substring(BEAN_METHOD_PROP_INDEX));
  96. }
  97. }