通过反射获取类上的注解信息

import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
public class DeviceBrandsVo {
@ApiModelProperty(value = "品牌名称")
    private String brandName;

    @ApiModelProperty(value = "品牌介绍")
    private String brandDesc;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @ApiModelProperty(value = "创建时间")
    private String createTime;

    @ApiModelProperty(value = "创建人")
    private Long creatorId;
    @ApiModelProperty(value = "创建人名称")
    private String creatorName;
    @ApiModelProperty(value = "是否删除 1正常 2删除")
    private Integer isDelete;

}



  public static void main(String[] args) {
        DeviceBrandsVo deviceBrandsVo = new DeviceBrandsVo();
        List<String> stringList = test(deviceBrandsVo);
        for (String s : stringList) {
            System.out.println(s);
        }
    }







import com.ruoyi.project.device.domain.newVo.DeviceBrandsVo;
import io.swagger.annotations.ApiModelProperty;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
//入参 类对象
public static List<String> test(Object object) {
        List<String> annotationList = new ArrayList<>();
        Class c1 = object.getClass();
        System.out.println(c1.getName());
        try {
            Class clazz = Class.forName(c1.getName());
            Field[] field02 = clazz.getDeclaredFields(); // 返回所有的属性
            for (Field field : field02) {
                String filedName = field.getName();
                // System.out.println(field.getName());

                Annotation annotation = field.getAnnotation(ApiModelProperty.class);
                //有该类型的注解存在  
                if (annotation != null) {
                    //强制转化为相应的注解      
                    ApiModelProperty xmlElement = (ApiModelProperty) annotation;
                    //3、获取属性上的指定类型的注解的指定方法  
                    //具体是不是默认值可以去查看源代码  
                    //System.out.println("属性【" + filedName + "】的注释: " + xmlElement.value());
                    annotationList.add("属性【" + filedName + "】的注释: " + xmlElement.value());
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return annotationList;
    }

你可能感兴趣的:(java)