首页 > 其他 > 详细

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

时间:2014-11-24 15:14:32      阅读:119      评论:0      收藏:0      [点我收藏+]

/**
  * 通过反射,给对象赋值
  * 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); 
        } 
    }

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

原文:http://www.cnblogs.com/holdon521/p/4118587.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!