List实体循环累加并返回实体

    xiaoxiao2022-07-05  161

    最近一段时间都在做统计(做到吐),其中遇到一个问题(主要是想偷懒),就是在List<Entity>中的实体内有将近20个int字段需要累加求和并返回一个该实体,不多说看代码

    首先创建一个Add的注解,虽然他实质是个接口

    import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by Dingxinyao on 2019/5/22 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Add { }

    @Reteniton的作用是定义被它所注解的注解保留多久,一共有三种策略,源码如下:

    /** * Annotation retention policy. The constants of this enumerated type * describe the various policies for retaining annotations. They are used * in conjunction with the {@link Retention} meta-annotation type to specify * how long annotations are to be retained. * * @author Joshua Bloch * @since 1.5 */ public enum RetentionPolicy { /** * Annotations are to be discarded by the compiler. */ SOURCE, /** * Annotations are to be recorded in the class file by the compiler * but need not be retained by the VM at run time. This is the default * behavior. */ CLASS, /** * Annotations are to be recorded in the class file by the compiler and * retained by the VM at run time, so they may be read reflectively. * * @see java.lang.reflect.AnnotatedElement */ RUNTIME }

    @Target说明了Annotation所修饰的对象范围:Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数),用于描述注解的使用范围

     

    然后在实体内的属性名上加@Add标签,就是上面定义的类名

    @Entity @Table(name = "Entity") public class Entity{ private String id; private String name; @Add private Integer num1; @Add private Integer num2; @Add private Integer num3; @Add private Integer num4; }

    下面就是最关键也是最重要的一步:

    注意,下面代码需要引用apache的common-lang3 jar包的FieldUtils工具类

    maven项目引用如下:

    <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency> public <E>E ListEntityAdd(@NonNull Collection<E> list, E t){ Field[] fields = FieldUtils.getFieldsWithAnnotation(t.getClass(),Add.class); for (E e : list) { for (Field field : fields) { String fieldName = field.getName(); try { int value = (int)FieldUtils.readDeclaredField(e,fieldName,true); int valueTotal = FieldUtils.readDeclaredField(t,fieldName,true) == null ? 0 : (int)FieldUtils.readDeclaredField(t,fieldName,true); FieldUtils.writeDeclaredField(t,fieldName,valueTotal+value,true); } catch (IllegalAccessException e1) { e1.printStackTrace(); } } } return t; }

     

    最新回复(0)