[关闭]
@File 2020-04-10T03:48:52.000000Z 字数 1096 阅读 32

反射复制对象

骚操作


复制一个POJO类

  1. /**
  2. * 克隆自定义对象
  3. * @param bean 自定义对象实例
  4. * @return 新的实例
  5. * @throws Exception
  6. */
  7. public static <T> T cloneBean(T bean) throws Exception {
  8. Class<?> cls = bean.getClass();
  9. T newBean = (T) cls.newInstance();
  10. // 拿到所有属性对象
  11. List<Field[]> fieldsList = getBeanAllFieldsList(cls);
  12. for (Field[] fields : fieldsList) {
  13. for (Field field : fields) {
  14. // 属性名
  15. String name = field.getName();
  16. // 首字母大写
  17. String firstLetter = name.substring(0, 1).toUpperCase();
  18. // 取get/set方法名
  19. String getMethodName = "get" + firstLetter + name.substring(1);
  20. String setMethodName = "set" + firstLetter + name.substring(1);
  21. // 取get/set方法对象
  22. Method getMethod = cls.getMethod(getMethodName);
  23. Method setMethod = cls.getMethod(setMethodName, field.getType());
  24. // 取旧对象的值
  25. Object value = getMethod.invoke(bean);
  26. if(Objects.isNull(value)) { continue; }
  27. // 赋值给新对象
  28. setMethod.invoke(newBean, value);
  29. }
  30. }
  31. return newBean;
  32. }
  33. /**
  34. * 取一个类的所有属性以及继承的父类属性
  35. * @param cls 类
  36. * @return 属性数组列表
  37. * @throws Exception
  38. */
  39. private static List<Field[]> getBeanAllFieldsList(Class<?> cls) throws Exception {
  40. List<Field[]> list = new ArrayList<>();
  41. //向上循环,遍历父类
  42. for (; cls != Object.class; cls = cls.getSuperclass()) {
  43. list.add(cls.getDeclaredFields());
  44. }
  45. return list;
  46. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注