一个反射方法应用实例

需求:在导出的时候,需要将list中的对象值赋给数组对象,返回一个数组集合
  • 原先的代码,在每一个导出的方法下需要写一个这样的转换方法
private List<Object> transBean2ObjectGradeNumber(List<GradeNumberOfPeopleStatistical> list) {
        List<Object> retList = new ArrayList<Object>();
        if (list == null || list.isEmpty()) {
            Object[] objs = new Object[6];
            retList.add(objs);
            return retList;
        }
        Object[] objs = null;
        for (GradeNumberOfPeopleStatistical temp : list) {
            objs = new Object[6];
            int index = 0;
            objs[index++] = temp.getGradeTypeName();
            objs[index++] = temp.getTotalClass();
            objs[index++] = temp.getMen();
            objs[index++] = temp.getWomen();
            objs[index++] = temp.getMenWomenProportion();
            objs[index++] = temp.getTotalPeople();
            retList.add(objs);
        }
        return retList;
    }
  • 新的运用反射的方法,该方法为公共的方法
private List<Object> transBean2ObjectExport(List<?> list,String[] methodNames) throws Exception {
        List<Object> retList = new ArrayList<Object>();
        if (list == null || list.isEmpty()) {
            Object[] objs = new Object[methodNames.length];
            retList.add(objs);
            return retList;
        }
        Object[] objs = null;

        for (Object object : list) {
            objs = new Object[methodNames.length];
            Class<? extends Object> cls = object.getClass();
            for (int i = 0; i <  methodNames.length ; i++ ) {
                Method method = cls.getMethod("get" + methodNames[i].substring(0,1).toUpperCase() + methodNames[i].substring(1));
                objs[i] = method.invoke(object);
            }
            retList.add(objs);

        }
        return retList;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值