カスタム注釈とリフレクションを使用して特定のフィールドの合計数を計算します

達成された成果

ここに画像の説明を挿入します

アイデアを整理する

全体のアイデア

  1. 注釈により、計算に使用されるフィールドを識別できます
  2. リフレクションを使用して、計算する必要があるフィールドの値を取り出し、それらを合計します。

ここで知っておく必要がある知識ポイントには、アノテーションと Java リフレクションが含まれます。リフレクションを使用してオブジェクトをインスタンス化し、値を取得し、値を割り当てます。

コード設計

  1. 計算する必要があるフィールドを識別するアノテーションを作成します。
  2. 特定のタイプのフィールド (合計を計算する必要がある JavaBeans) を取得し、フィールドをループして、注釈付きフィールドを取得します。
  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}]

ここに画像の説明を挿入します

上記のツールクラスによれば、任意のリストを渡して合計数を計算することができます。それが最後の行の合計です。
このようにして、統計リストを持つビジネスを個別に扱う必要はありません。

おすすめ

転載: blog.csdn.net/weixin_40741732/article/details/128849984