1. 程式人生 > 其它 >反射獲取類屬性上的註解

反射獲取類屬性上的註解

在工作中用到easyexcel,有一個上傳檔案的功能,新模板比舊模板多了一列,因此產生當使用之前的舊模板時要拒掉,不能向下執行

程式中對映的實體類使用@ExcelProperty(value = "*二維碼編號", index = 0)註解,用於標識excel檔案列的順序。

針對這個功能首先要獲取實體類的屬性上註解的內容,將內容與表頭內容進行匹配。

public static void main(String[] args) {
        //獲取單表頭的實體類順序
        Class clazz = QrcodeUpdateParamsDto.class;
        //獲取類的所有屬性
Field[] declaredFields = clazz.getDeclaredFields(); List<FieldExcelProperty> fieldExcelPropertyList = new ArrayList<>(); FieldExcelProperty fieldExcelProperty = null; for (Field field: declaredFields) { System.out.println(field.toString()); ExcelProperty annotation
= field.getAnnotation(ExcelProperty.class); if (annotation != null) { fieldExcelProperty = new FieldExcelProperty(); fieldExcelProperty.setIndex(annotation.index()); fieldExcelProperty.setValue(annotation.value()); fieldExcelPropertyList.add(fieldExcelProperty); fieldExcelProperty
= null; } } if (!fieldExcelPropertyList.isEmpty()) { //利用拉姆達表示式,進行排序,將排序後的結果輸出為list } }

自定義內部類,用於儲存屬性上註解的值

class FieldExcelProperty{
    private int index;
    private String[] value;

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public String[] getValue() {
        return value;
    }

    public void setValue(String[] value) {
        this.value = value;
    }
}

這樣將實體類轉換為表頭資訊,再與讀取到的excel表頭做對比,headList為實體類對應的屬性集合。

 @Override
  public void invokeHeadMap(Map headMap, AnalysisContext context) {
    if (context.readRowHolder().getRowIndex() == 0) {
      for (int i = 0; i < headList.length; i++) {
        try {
          if (null != headMap &&
              null != headMap.get(i) &&
              !headMap.get(i).equals(headList[i])) {
            throw new ExcelAnalysisException("上傳模板與系統模板不匹配,請使用平臺模板上傳資料");
          }
        } catch (Exception e) {
          throw new ExcelAnalysisException(e.getMessage());
        }
      }
    }

  }

如果對比不一致,就會拒絕。