需要批注处理器的帮助。我已经创建了一个简单的批注处理器,它使用@autoservice批注来检查被批注的字段是否为final。但是它没有显示任何编译时错误。这是我的配置
注释:
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.FIELD)
public @interface Store {
int temp() default 0;
}批注处理器:
@SupportedAnnotationTypes("com.self.Store")
@AutoService(Processor.class)
public class Process extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (Element element : roundEnv.getElementsAnnotatedWith(Store.class)) {
TypeElement typeElement = (TypeElement) element;
for (Element element2 : typeElement.getEnclosedElements()) {
VariableElement variableElement = (VariableElement) element2;
if (!variableElement.getModifiers().contains(Modifier.FINAL)) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "it should be final");
}
}
}
return true;
}
}pom文件:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>annotations</groupId>
<artifactId>annotations</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>annotation</name>
<dependencies>
<dependency>
<groupId>com.google.auto.service</groupId>
<artifactId>auto-service</artifactId>
<version>1.0-rc2</version>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>测试文件:
public class Test {
@Store
public int id;
}发布于 2019-06-09 08:18:38
根据Baeldung的topic on annotation processor development,你必须首先配置你的maven编译器插件,并在那里声明自动服务注释处理器。这就是缺失的一步。仅供参考,如果你使用的是Gradle,你可以在依赖闭包下面声明它:
dependencies {
annotationProcessor 'com.google.auto.service:auto-service:1.0-rc5'
compile 'com.google.auto.service:auto-service:1.0-rc5'
}发布于 2017-06-14 04:39:39
看起来你漏掉了一步。运行此项目的Maven build将调用Google AutoService注释处理器,为您的custom processor创建一个registration file,并使用它构建一个.jar。为了让处理器正常工作,在编译包含Test的项目之前,必须将该.jar作为依赖项包括在内。否则,必须由Java ServiceLoader拾取的注册文件是在编译过程中生成的,显然不包括在编译器的类路径中。
https://stackoverflow.com/questions/44530648
复制相似问题