簡體   English   中英

如何從注釋處理器中讀取枚舉常量的值?

[英]How to read values of enum constants from annotation processor?

我正在做一個項目,我的主管希望我能夠通過注釋處理器獲取枚舉常量的值。 例如來自以下枚舉定義:

public enum Animal {
    LION(5),
    GIRAFFE(7),
    ELEPHANT(2),

    private int value;

    Animal(int value) {
        this.value = value;
    }

    public int Value() {
        return value;
    }
}

他們要我編譯一個 [5, 7, 2] 的數組。

請注意,因為我在注釋處理器中工作,所以我使用的是基於元素的反射(不是基於Class的反射)。

我對VariableElement文檔的閱讀使我相信這是不可能的。

請注意,並非所有最終字段都具有恆定值。 特別是,枚舉常量不被視為編譯時常量。

有誰知道讓這個工作的方法?

感謝您抽出時間來閱讀! ——貝卡

我們最終為這個項目做的是我們在運行注釋處理器之前編譯了所有的枚舉。 如果在運行注釋處理器之前已經編譯了 class,則可以使用基於Class的反射訪問有關它的信息。

在這種情況下,首先編譯枚舉是可行的,因為枚舉的類被傳遞給其他類的注釋(枚舉用於定義一些下拉菜單)。

這是用於獲取枚舉常量名稱及其值的代碼。 其中 optionElem 是表示枚舉 class 的元素。

private <E extends Enum<E>> boolean tryAddOptionList(Element optionElem) {
    String className = optionElem.asType().toString();

    // Get the class.
    Class clazz = null;
    try {
      clazz = Class.forName(className);
    } catch (ClassNotFoundException e) {
      throw new IllegalArgumentException("OptionList Class: " + className + " is not available. " +
        "Make sure that it is available to the compiler.");
    }
    if (clazz == null) {
      return false;
    }

    // Get the getValue method.
    java.lang.reflect.Method getValueMethod = null;
    try {
      getValueMethod = clazz.getDeclaredMethod("getValue", new Class[] {});
    } catch (NoSuchMethodException e) {
      throw new IllegalArgumentException("Class: " + className + " must have a getValue() method.");
    }
    if (getValueMethod == null) {
      return false;
    }

    // Create a map of enum const names -> values.
    Map<String, String> namesToValues = Maps.newTreeMap();
    Object[] constants = clazz.getEnumConstants();
    for (Object constant : clazz.getEnumConstants()) {
        try {
          E enumConst = (E) constant;
          namesToValues.put(
            enumConst.name(),
            getValueMethod.invoke(enumConst, new Object [] {}).toString());
        } catch (Exception e) {}
    }
    // etc...
}

如果您想要更多上下文,這里是完整的拉取請求。 實際的枚舉解析由 ComponentProcessor 文件處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM