利用自定义注解和反射计算出某些字段总数

实现的效果

在这里插入图片描述

思路整理

整体思路

  1. 注解可以标识哪些字段是用于计算的
  2. 通过反射拿出需要计算字段的值,并加起来即可

这里需要了解的知识点有注解、java反射。利用反射实例化对象、获取值和赋值。

代码设计

  1. 创建一个注解,用于分辨需要计算的字段。
  2. 获取某类类型(需要计算总数的javabean)的字段,循环字段并拿到带注解的字段。
  3. 利用java8计算总数的功能,把需要计算的字段传入进去,将总数计算出来。
  4. 利用反射的实例化创建新的对象,并将上面计算的总数赋值进去,返回这个对象即可。

代码实现

核心代码
// 获取字段列表
Class c;
List<Field> fields = Arrays.stream(c.getDeclaredFields()).collect(Collectors.toList());
// 根据类型实例化队形
Constructor constructor = c.getConstructor();
obj = constructor.newInstance();
// 获取字段的注解
FieldTotalAnnotation annotation = field.getAnnotation(FieldTotalAnnotation.class);
// 根据方法名获取属性值
String getMethodName = "get"
        + propertyName.substring(0, 1).toUpperCase()
        + propertyName.substring(1);
Method method = data.getMethod(getMethodName);
Object value = method.invoke(v);
// 根据方法名为属性赋值
String setMethodName = "set"
                + propertyName.substring(0, 1).toUpperCase()
                + propertyName.substring(1);
Class<?> resType = c.getDeclaredField(propertyName).getType();
            Method method = c.getMethod(setMethodName, resType);
  method.invoke(obj, (String) value);
完整代码
@Slf4j
public class StatisticTotalUtil {
    /**
     * @param statisticsTotalList 需要计算的列表
     * @param c                   需要创建新对象的类型
     * @return 返回一个新的对象 里面是各个字段的总数
     */
    public static <T> T getTotalCount(List<T> statisticsTotalList, Class c) {
        statisticsTotalList.stream().mapToInt(v -> {
            return (int) new Object();
        });
        // 获取字段列表
        List<Field> fields = Arrays.stream(c.getDeclaredFields()).collect(Collectors.toList());
        // 创建总计对象
        Object res = new Object();
        try {
            Constructor constructor = c.getConstructor();
            res = constructor.newInstance();
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        Object finalRes = res;
        fields.stream().forEach(field -> {
            FieldTotalAnnotation annotation = field.getAnnotation(FieldTotalAnnotation.class);
            if (ObjectUtil.isEmpty(annotation)) {
                return;
            }
            Class<?> type = field.getType();
            String propertyName = field.getName();
            if (ObjectUtil.isNotEmpty(annotation) && annotation.value() && !annotation.isTotalName()) {
                if (type != Integer.class) {
                    log.info("不是[Integer]类型不予累加");
                    return;
                }
                Object sum = statisticsTotalList.stream().mapToInt(v -> {
                    Class data = v.getClass();
                    try {
                        // 根据属性名称就可以获取其get方法
                        String getMethodName = "get"
                                + propertyName.substring(0, 1).toUpperCase()
                                + propertyName.substring(1);
                        Method method = data.getMethod(getMethodName);
                        Object value = method.invoke(v);
                        return (int) Optional.ofNullable(value).orElse(0);
                    } catch (NoSuchMethodException e) {
                        throw new RuntimeException(e);
                    } catch (InvocationTargetException e) {
                        throw new RuntimeException(e);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }).sum();
                setPropertyValue(propertyName, finalRes, c, type, sum);
            } else {
                log.info("没有统计注解标识或者不是integer类型");
            }
            if (ObjectUtil.isNotEmpty(annotation) && annotation.isTotalName()) {
                if (type != String.class) {
                    log.info("不是[String]类型不予累加");
                    return;
                }
                setPropertyValue(propertyName, finalRes, c, type, "总计");
            } else {
                log.info("没有统计注解标识或者不是String类型");
            }

        });
        return (T) res;
    }

    /**
     * @param propertyName 某字段的属性名称
     * @param finalRes     用传过来的对象类型创建的对象
     * @param c            需要创建新对象的类型
     * @param type         需要赋值的字段类型
     * @param value        计算过后的值
     */
    private static void setPropertyValue(String propertyName, Object finalRes, Class c, Class type, Object value) {
        String setMethodName = "set"
                + propertyName.substring(0, 1).toUpperCase()
                + propertyName.substring(1);
        try {
            Class<?> resType = c.getDeclaredField(propertyName).getType();
            Method method = c.getMethod(setMethodName, resType);
            if (type == Integer.class) {
                method.invoke(finalRes, (int) value);
            }
            if (type == String.class) {
                method.invoke(finalRes, (String) value);
            }
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }

}
@Documented
@Target(ElementType.FIELD)// 作用在字段上
@Retention(RetentionPolicy.RUNTIME)// 运行时有效
public @interface FieldTotalAnnotation {
    @ApiModelProperty("是否需要统计")
    boolean value() default true;
    @ApiModelProperty("是否需要加上”合计“两个字")
    boolean isTotalName() default false;
}
@Test
public void statisticTotal() {
    List<TMessageTemplateStatistic> resList = new ArrayList<>();
    TMessageTemplateStatistic s1 = new TMessageTemplateStatistic();
    s1.setTotalCount(4);
    s1.setMailCount(5);
    TMessageTemplateStatistic s2 = new TMessageTemplateStatistic();
    s2.setTotalCount(7);
    s2.setMailCount(8);
    resList.add(s1);
    resList.add(s2);
    TMessageTemplateStatistic total = StatisticTotalUtil.getTotalCount(resList, TMessageTemplateStatistic.class);
    resList.add(total);
    System.out.println(resList);
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class TMessageTemplateStatistic implements Serializable {

    @FieldTotalAnnotation(isTotalName = true)
    @ApiModelProperty("区域名称")
    private String areaName;

    @FieldTotalAnnotation
    @ApiModelProperty("总数量")
    private Integer totalCount;

    @FieldTotalAnnotation
    @ApiModelProperty("发送邮政企业数量")
    private Integer mailCount;

}
[{"areaName":"杭州","mailCount":5,"totalCount":4},{"areaName":"台州","mailCount":8,"totalCount":7},{"areaName":"总计","mailCount":13,"totalCount":11}]

在这里插入图片描述

根据上面的工具类可以传任何列表,都可以计算出总数。就是最后一行的总计。
这样就不用遇到一个带统计列表的业务单独处理了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值