0
点赞
收藏
分享

微信扫一扫

使用反射来统计汇总行数据

王远洋 2022-03-24 阅读 143
java

分期允许多选,按分期维度时同一个分期下的数据就会在两条数据中,总计里面也要统计两次,所以只能最后手动合计。

private void calculateSummary(Object statistics, Object summary) {
        try {
            Class<?> statisticsClazz = statistics.getClass();
            Class<?> summaryClazz = summary.getClass();
            Field[] fields = statisticsClazz.getDeclaredFields();
            for (Field field : fields) {
                if (!field.getType().toString().equals("class java.lang.Integer")) {
                    continue;
                }
               
                Method summarySetMethod = summaryClazz.getMethod("set" + getMethodName(field.getName()));
                Method statisticsGetMethod = statisticsClazz.getMethod("get" + getMethodName(field.getName()));
                Method summaryGetMethod = summaryClazz.getMethod("get" + getMethodName(field.getName()));
                Integer statisticsValue = (Integer) statisticsGetMethod.invoke(statisticsClazz);
                Integer summaryValue = (Integer) summaryGetMethod.invoke(summaryClazz);
                summarySetMethod.invoke(summaryClazz, statisticsValue + summaryValue);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 将首字母转换为大写
    private static String getMethodName(String fieldName) throws Exception {
        byte[] items = fieldName.getBytes();
        items[0] = (byte) ((char) items[0] - 'a' + 'A');
        return new String(items);
    }
举报

相关推荐

0 条评论