将List集合中,含有BigDeciam字段求和

  该方法采用反射创建对象,并进行赋值,将List<T>,中含有BigDecimal字段的值求和,并赋值到新的对象中对应的字段上。

  代码如下:

 @SneakyThrows
    public static <T> T convertListValueToObjectValue(List responses, Class<T> clazz) {
        Object object = clazz.newInstance();
        Class<?> aClass = object.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            if ("java.math.BigDecimal".equals(declaredField.getType().getName())) {
                declaredField.setAccessible(true);
                for (Object row : responses) {
                    Field[] rowFields = row.getClass().getDeclaredFields();
                    for (Field rowField : rowFields) {
                        if ("java.math.BigDecimal".equals(rowField.getType().getName()) && rowField.getName().equals(declaredField.getName())) {
                            rowField.setAccessible(true);
                            BigDecimal tem = (BigDecimal) rowField.get(row);
                            BigDecimal dst = (BigDecimal) declaredField.get(object);
                            declaredField.set(object, tem.add(dst));
                        }
                    }
                }
            }
        }
        return (T) object;
    }

 

posted @ 2021-02-03 17:54  九星  阅读(3411)  评论(0编辑  收藏  举报