Java反射复制一个数据对象

来源:互联网 发布:盐城平面软件培训 编辑:程序博客网 时间:2024/04/30 20:44
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;} }

0 0
原创粉丝点击