简体   繁体   English

如何从注释处理器中读取枚举常量的值?

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

I'm working on a project, and my supervisors want me to be able to get the values of enum constants via an annotation processor.我正在做一个项目,我的主管希望我能够通过注释处理器获取枚举常量的值。 For example from the following enum definition:例如来自以下枚举定义:

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

    private int value;

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

    public int Value() {
        return value;
    }
}

They want me to compile an array of [5, 7, 2].他们要我编译一个 [5, 7, 2] 的数组。

Note that because I am working within an annotation processor, I am using Element based reflection (not Class based reflection).请注意,因为我在注释处理器中工作,所以我使用的是基于元素的反射(不是基于Class的反射)。

My reading of the VariableElement documentation leads me to believe this is impossible.我对VariableElement文档的阅读使我相信这是不可能的。

Note that not all final fields will have constant values.请注意,并非所有最终字段都具有恒定值。 In particular, enum constants are not considered to be compile-time constants.特别是,枚举常量不被视为编译时常量。

Does anyone know of a way to get this working?有谁知道让这个工作的方法?

Thank you for taking the time to read this!感谢您抽出时间来阅读! --Beka ——贝卡

What we ended up doing for this project is we compiled all of the enums before running the annotation processor.我们最终为这个项目做的是我们在运行注释处理器之前编译了所有的枚举。 If a class has already been compiled before you run the annotation processor, it is possible to access information about it using Class based reflection.如果在运行注释处理器之前已经编译了 class,则可以使用基于Class的反射访问有关它的信息。

Compiling the enums first was workable in this case because the enums' classes were passed to annotations on other classes (the enums are used to define some dropdowns).在这种情况下,首先编译枚举是可行的,因为枚举的类被传递给其他类的注释(枚举用于定义一些下拉菜单)。

Here is the code used to get the names of enum constants and their values.这是用于获取枚举常量名称及其值的代码。 Where optionElem is the Element representing the enum 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...
}

Here is the full pull request if you would like more context.如果您想要更多上下文,这里是完整的拉取请求。 The actually enum parsing is handled by the ComponentProcessor file.实际的枚举解析由 ComponentProcessor 文件处理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从注释处理器中的嵌套注释中读取Class []值 - How to read a Class[] values from a nested annotation in an annotation processor 如何从注释处理器中的AnnotationValue捕获枚举 - How to capture an Enum from an AnnotationValue in an Annotation Processor 注释处理器:从 TypeMirror 或 TypeElement 获取所有枚举值 - Annotation processor: get all enum values from a TypeMirror or TypeElement Java 注释处理器:如何从注释中提取 class 值 - Java Annotation Processor: how to extract class values from an annotation 如何使用注释处理器从 src/main/resources 读取文件? - How to read file from src/main/resources with annotation processor? 如何从Java中分配给它们的值中检索枚举常量? - How to retrieve Enum Constants from values assigned to them in Java? 如何从ProGuard中排除注释处理器依赖项 - How to exclude an annotation processor dependency from ProGuard 如何让java注释处理器从projectA读取和处理注释,并为projectB生成java源文件 - How to have a java annotation processor read and process annotations from projectA and generate java source files for projectB 在注释中直接使用注释处理器生成的常量会导致编译错误 - Use annotation processor generated constants indrectly in annotation will lead compile error Kotlin - 如何从注释处理器获取 KClass&lt;*&gt; 注释参数 - Kotlin - How to get KClass<*> annotation parameter from annotation processor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM