您的位置:首页 > 其它

通过反射,给对象之间赋值

2014-11-24 14:18 369 查看
/**
* 通过反射,给对象赋值
* add by wangHao 2014-01-08
* @param source
* @param dest
* @throws Exception
*/
public void CopyObject(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++){
if( "id".equals(sourceProperty[i].getName())){
continue;
}
for(int j=0;j<destProperty.length;j++){
if(sourceProperty[i].getName().equals(destProperty[j].getName())){
destProperty[j].getWriteMethod().invoke(dest, sourceProperty[i].getReadMethod().invoke(source));
break;
}
}
}
}catch(Exception e){
throw new Exception("属性复制失败:",e);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: