注释 - 在构建时读取元素值

Joe*_*dev 6 java annotations

是否可以在构建时读取注释元素的值?例如,如果我定义了以下注释:

public @interface State {
    String stage();
}
Run Code Online (Sandbox Code Playgroud)

我在类中注释一个方法,如下所示:

public class Foo {
   @State(stage = "build")
   public String doSomething() {
      return "doing something";
   }
}
Run Code Online (Sandbox Code Playgroud)

如何在构建时在注释处理器中读取@State注释元素'stage' 的?我有一个如下构建的处理器:

@SupportedAnnotationTypes(value = {"State"})
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class StageProcessor extends AbstractProcessor { 
    @Override
    public boolean process(Set<? extends TypeElement> elementTypes,
            RoundEnvironment roundEnv) {
        for (Element element : roundEnv.getRootElements()) {
               // ... logic to read the value of element 'stage' from
               // annotation 'State' in here.
        }
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

Pac*_*ace 6

不是最好的答案,因为我自己没有这样做,但看到已经3个小时,我会尽我所能.

注释处理概述

除非使用-proc:none选项禁用注释处理,否则编译器将搜索可用的任何注释处理器.可以使用-processorpath选项指定搜索路径; 如果未给出,则使用用户类路径.处理器通过
搜索路径上名为META-INF/services/javax.annotation.processing.Processor 的服务提供者配置文件来定位.此类文件应包含要使用的任何注释处理器的名称,每行列出一个.或者,可以使用-processor选项显式指定处理器.

因此,您似乎需要javax.annotation.processing.ProcessorMETA-INF/services文件夹中创建一个文件,该文件列出了注释处理器的名称,每行一个.

编辑:那么我相信读取注释的代码将是...

    for (Element element : roundEnv.getRootElements()) {
        State state = element.getAnnotation(State.class);
        if(state != null) {
            String stage = state.stage();
            System.out.println("The element " + element + " has stage " + stage);
        }
    }
Run Code Online (Sandbox Code Playgroud)

可以在此处找到注释处理器的真实示例.