您的位置:首页 > 编程语言 > Java开发

java两个对象中相同的属性值复制

2014-06-26 17:03 127 查看
/**
* 两个对象中相同的属性值复制
* @param source
* @param dest
* @throws Exception
*/
public static void Copy(Object source, Object dest)throws Exception {
//获取属性
BeanInfo sourceBean = Introspector.getBeanInfo(source.getClass(), java.lang.Object.class);
PropertyDescriptor[] sourceProperty = sourceBean.getPropertyDescriptors();

BeanInfo destBean = Introspector.getBeanInfo(dest.getClass(), java.lang.Object.class);
PropertyDescriptor[] destProperty = destBean.getPropertyDescriptors();

try{
for(int i=0;i<sourceProperty.length;i++){

for(int j=0;j<destProperty.length;j++){

if(sourceProperty[i].getName().equals(destProperty[j].getName())){
//调用source的getter方法和dest的setter方法
destProperty[j].getWriteMethod().invoke(dest, sourceProperty[i].getReadMethod().invoke(source));
break;
}
}
}
}catch(Exception e){
throw new Exception("属性复制失败:"+e.getMessage());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: