复制类的类方法

来源:互联网 发布:万网云新建数据库 编辑:程序博客网 时间:2024/06/01 16:53
public  Object copy(Object object) throws Exception {
Class<?> classType = object.getClass();
Object objectCopy = classType.getConstructor(new Class[] {}).newInstance(new Object[] {});
Field[] fields = classType.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
String fieldName = field.getName();
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getMethodName = "get" + firstLetter + fieldName.substring(1);
String setMethodName = "set" + firstLetter + fieldName.substring(1);
Method getMethod = classType.getMethod(getMethodName,new Class[] {});
Method setMethod = classType.getMethod(setMethodName,new Class[] { field.getType() });
Object value = getMethod.invoke(object, new Object[] {});
setMethod.invoke(objectCopy, new Object[] { value });
}
return objectCopy;
0 0
原创粉丝点击