import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Test {
public static 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;
}
}
Java反射复制一个数据对象
最新推荐文章于 2022-12-02 09:51:24 发布