数据源复制Util
有时候我们在开发过程中经常会遇到,将一个对象的数据复制到另外一个对象里面去,比如要讲一个对象的数据复制到一个历史记录表里面去,如果我们用set,get就比较麻烦,用这个目前类的前提是,javaBean实体里面的属性是相同的才可以复制,这样可以大大提高了我们在开发过程中的数据操作时间。
import java.lang.reflect.Method;
/**
* 数据源复制util
* @author weidetian
* @version 2013-12-16
*/
public class BeanUtil {
public static void copyProperties(Object source, Object dest)
throws Exception {
Method[] sourceMethod = source.getClass().getMethods();
Method[] destMethod = dest.getClass().getMethods();
String sourceMethodName, methodFix1, destMethodName2, methodFix2;
for (int i = 0; i < sourceMethod.length; i++) {
sourceMethodName = sourceMethod[i].getName();
methodFix1 = sourceMethodName.substring(3,
sourceMethodName.length());
if (sourceMethodName.startsWith("get")) {
for (int j = 0; j < destMethod.length; j++) {
destMethodName2 = destMethod[j].getName();
methodFix2 = destMethodName2.substring(3,
destMethodName2.length());
if (destMethodName2.startsWith("set")) {
if (methodFix2.equals(methodFix1)) {
Object[] objs2 = new Object[1];
objs2[0] = sourceMethod[i].invoke(source,
new Object[0]);
// 只copy不为空的值
if (null != objs2[0]) {
destMethod[j].invoke(dest, objs2);
}
continue;
}
}
}
}
}
}
} 相关推荐
yangkang 2020-11-09
lbyd0 2020-11-17
KANSYOUKYOU 2020-11-16
wushengyong 2020-10-28
腾讯soso团队 2020-11-06
Apsaravod 2020-11-05
PeterChangyb 2020-11-05
gyunwh 2020-11-02