Java gets all the fields of the entity, and the corresponding annotation value

1. Entity attributes

@Data
@Table(name = "user")
@ApiModel(value="用户表")
public class User {
    
    

    private static final long serialVersionUID = 1L;

    @ApiModelProperty("用户名")
    private String username;

    @ApiModelProperty("密码")
    private String password;

    @ApiModelProperty(value = "创建人")
    private String crtUser;

    @ApiModelProperty(value = "创建时间")
    private Date crtTime;

    @ApiModelProperty(value = "修改人")
    private String updUser;

    @ApiModelProperty(value = "修改时间")
    private Date updTime;
    
}

2. Obtain entity attributes and annotation values

    /**
     * description 获取实体的所有字段,和对应注解值
     *
     * @param object 实体
     * @author yanzy
     * @version 1.0
     * @date 2021/3/24 15:47
     */
    public static Map<String, String> getFieldAnnotation(Object object) {
    
    
        Field[] fields = object.getClass().getDeclaredFields();
        Map<String, String> resultMap = new HashMap();
        for (Field field : fields) {
    
    
            // 是否引用ApiModelProperty注解
            boolean bool = field.isAnnotationPresent(ApiModelProperty.class);
            if (bool) {
    
    
                String value = field.getAnnotation(ApiModelProperty.class).value();
                resultMap.put(field.getName(), value);
            }
        }
        return resultMap;
    }

3. Execute the program, and you can see that the attribute and the annotation value of the attribute have been obtained
insert image description here

4. There are many unnecessary fields in the entity, such as the creator, creation time, etc., which need to be filtered out and the code optimized

    /**
     * description 获取实体的所有字段,和对应注解值
     *
     * @param object    实体
     * @param filterMap 需要过滤的字段
     * @author yanzy
     * @version 1.0
     * @date 2021/3/24 15:47
     */
    public static Map<String, String> getFieldAnnotation(Object object, Map<String, String> filterMap) {
    
    
        Field[] fields = object.getClass().getDeclaredFields();
        Map<String, String> resultMap = new HashMap();
        for (Field field : fields) {
    
    
            if (!filterMap.containsValue(field.getName())) {
    
    
                // 是否引用ApiModelProperty注解
                boolean bool = field.isAnnotationPresent(ApiModelProperty.class);
                if (bool) {
    
    
                    String value = field.getAnnotation(ApiModelProperty.class).value();
                    resultMap.put(field.getName(), value);
                }
            }
        }
        return resultMap;
    }

5. Executing the program to filter out the creator and modifier
insert image description here
can see these two attributes, which have been filtered out

Guess you like

Origin blog.csdn.net/qq_39486119/article/details/115179376