@File
2020-04-10T03:48:52.000000Z
字数 1096
阅读 89
骚操作
/*** 克隆自定义对象* @param bean 自定义对象实例* @return 新的实例* @throws Exception*/public static <T> T cloneBean(T bean) throws Exception {Class<?> cls = bean.getClass();T newBean = (T) cls.newInstance();// 拿到所有属性对象List<Field[]> fieldsList = getBeanAllFieldsList(cls);for (Field[] fields : fieldsList) {for (Field field : fields) {// 属性名String name = field.getName();// 首字母大写String firstLetter = name.substring(0, 1).toUpperCase();// 取get/set方法名String getMethodName = "get" + firstLetter + name.substring(1);String setMethodName = "set" + firstLetter + name.substring(1);// 取get/set方法对象Method getMethod = cls.getMethod(getMethodName);Method setMethod = cls.getMethod(setMethodName, field.getType());// 取旧对象的值Object value = getMethod.invoke(bean);if(Objects.isNull(value)) { continue; }// 赋值给新对象setMethod.invoke(newBean, value);}}return newBean;}/*** 取一个类的所有属性以及继承的父类属性* @param cls 类* @return 属性数组列表* @throws Exception*/private static List<Field[]> getBeanAllFieldsList(Class<?> cls) throws Exception {List<Field[]> list = new ArrayList<>();//向上循环,遍历父类for (; cls != Object.class; cls = cls.getSuperclass()) {list.add(cls.getDeclaredFields());}return list;}