Java获取实体的所有字段,和对应注解值

1、实体属性

@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、获取实体属性,和注解值

    /**
     * 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、执行程序,可以看到属性和属性的注解值都已经拿到
在这里插入图片描述

4、实体里面有很多不需要的字段,例如创建人、创建时间等等,都需要过滤掉,优化下代码

    /**
     * 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、执行程序过滤掉创建人和修改人
在这里插入图片描述
可以看到这两个属性,已经被过滤掉了

猜你喜欢

转载自blog.csdn.net/qq_39486119/article/details/115179376
今日推荐