博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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

Posted on 2019-08-19 16:20  XYH0809  阅读(801)  评论(0)    收藏  举报

/**
    * 两个对象中相同的属性值复制
    * @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());
            }
        }  
    
    
    public static void main(String[] args) throws Exception {
        MenuConf menuConf = new MenuConf();
         List<MenuConf> nextLevelList = new ArrayList<MenuConf>();
        
        
        FirstMenuConfig firstMenuConfig = new FirstMenuConfig();
        firstMenuConfig.setTitle("XYH-------------");
        List<SndMenuConfig> sndMenuConfigs = new ArrayList<SndMenuConfig>();
        SndMenuConfig sndMenuConfig1 = new SndMenuConfig();
        sndMenuConfig1.setTitle("二级菜单");
        sndMenuConfigs.add(sndMenuConfig1);
        SndMenuConfig sndMenuConfig2 = new SndMenuConfig();
        sndMenuConfig2.setTitle("二级菜单22");
        sndMenuConfigs.add(sndMenuConfig2);
        firstMenuConfig.setSndMenuConfigs(sndMenuConfigs);
       //一级菜单
        copy(firstMenuConfig, menuConf);
       //二级菜单
        for(SndMenuConfig sndMenuConfig :sndMenuConfigs) {
            MenuConf menuConf1 = new MenuConf();
            copy(sndMenuConfig, menuConf1);
            nextLevelList.add(menuConf1);
        }
        menuConf.setNextLevelList(nextLevelList);
        System.out.println(menuConf.getTitle());
        for(MenuConf mc : menuConf.getNextLevelList()) {
            System.out.println(mc.getTitle());
        }
    }