通過反射獲取類上的註解信息

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;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章