gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:15:06 24 4
gpt4 key购买 nike

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

public @interface State {
String stage();
}

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

public class Foo {
@State(stage = "build")
public String doSomething() {
return "doing something";
}
}

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

@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;
}
}

最佳答案

这不是最佳答案,因为我自己还没有这样做,但鉴于已经过去 3 个小时,我会尽力而为。

Overview of annotation processing

Unless annotation processing is disabled with the -proc:none option, the compiler searches for any annotation processors that are available. The search path can be specified with the -processorpath option; if it is not given, the user class path is used. Processors are located by means of service provider-configuration files named
META-INF/services/javax.annotation.processing.Processor on the search path. Such files should contain the names of any annotation processors to be used, listed one per line. Alternatively, processors can be specified explicitly, using the -processor option.

看来您需要在 META-INF/services 文件夹中创建一个名为 javax.annotation.processing.Processor 的文件,其中列出了注释的名称处理器,每行一个。

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

    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);
}
}

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

关于java - 注释 - 在构建时读取元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6358179/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com