@File
2020-04-10T03:48:52.000000Z
字数 1096
阅读 32
骚操作
/**
* 克隆自定义对象
* @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;
}