问题描述
我正在编写一个简单的 Java 应用程序,其中如果我使用自定义 @Log
注释进行注释,某些类应该打印消息“在
@SupportedAnnotationTypes ("Log")
@AutoService({Processor.class})
public class LogProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public boolean process(Set<? extends TypeElement> annotations,RoundEnvironment roundEnv) {
for (TypeElement typeElement : annotations) {
for (Element element : roundEnv.getElementsAnnotatedWith(typeElement)) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,"found @Log annotation at " + element);
}
}
return true;
}
}
@Target (ElementType.TYPE)
public @interface Log {}
我正在使用 @AutoService
注册注释处理器。如何包含在运行 gradle 构建时生成的 .jar 文件?我尝试了以下方法:
repositories {
mavenCentral()
flatDir {
dirs 'libs'
}
}
dependencies {
annotationProcessor name: 'Annotationsupplier-1.0-SNAPSHOT'
}
或
dependencies {
annotationProcessor files('/libs/Annotationsupplier-1.0-SNAPSHOT.jar')
}
但这不起作用,我不知道如何添加注释处理器 jar。我的期望是,在添加了 Annotationsupplier-1.0-SNAPSHOT 的情况下运行项目后,我应该能够在控制台中看到“在
解决方法
你可以试试这个作为解决方法:
implementation files('/path/to/custom-processor.jar')
annotationProcessor files('/path/to/custom-processor.jar')
,
对我来说,问题是通过在父项目下添加注释处理器模块(通过创建一个新模块)并在父项目 build.gradle
中添加以下内容来解决的:
dependencies {
annotationProcessor project(':AnnotationProcessor')
compile project(':AnnotationProcessor')
}
注 1:AnnotationProcessor 是我在父项目下创建的注释处理器模块的名称。
注意 2:我在 IntelliJ IDE 中执行此操作。
注意3:确保为项目开启注解处理