public class BeanCopyUtils {
/**
*
* copy:<br />
* 复制一个对象到另外一个
*
* @author zhangzhaoyu
* @param object
* @return
* @throws Exception
*/
public static void copy(Object org, Object des) throws Exception {
Class<?> orgClassType = org.getClass();
Class<?> desClassType = des.getClass();
//Object objectCopy = desClassType.getConstructor(new Class[]{}).newInstance(new Object[]{});
Field []fields = orgClassType.getDeclaredFields();
for (Field field : fields) {
String filedName = field.getName();
String firstLetter = filedName.substring(0, 1).toUpperCase();
String getMethodName = "get" + firstLetter + filedName.substring(1);
String setMethodName = "set" + firstLetter + filedName.substring(1);
Method getMethod = orgClassType.getMethod(getMethodName, new Class[]{});
Method setMethod = desClassType.getMethod(setMethodName, new Class[]{field.getType()});
if (getMethod != null) {
Object value = getMethod.invoke(org, new Object[]{});
if (setMethod != null) {
setMethod.invoke(des, new Object[]{value});
}
}
}
}
}
Java 反射实现对象拷贝
最新推荐文章于 2022-03-08 23:22:12 发布