我试图用普通的Java(而不是android api)制作注释处理器,但是每当我运行我的主要功能时,处理器就会因为错误而停止构建过程,但事实并非如此。
我的项目结构是:
Root
|-> core (all features including annotations)
|-> annotation-processors (just annotation processor with set-up META-INF and processor class)
|-> example (main void with class that is annotated with @Disable - annotation declared in core, this should stop compiler)
注释处理器类为
@SupportedAnnotationTypes("jacore.support.Disable")
@SupportedSourceVersion(SourceVersion.RELEASE_7)
public class Processor extends AbstractProcessor {
private Filer filer;
private Messager messager;
private Elements elements;
@Override
public synchronized void init(ProcessingEnvironment processingEnvironment) {
this.filer = processingEnvironment.getFiler();
this.messager = processingEnvironment.getMessager();
this.elements = processingEnvironment.getElementUtils();
}
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
for (Element element : roundEnvironment.getElementsAnnotatedWith(Disable.class)) {
if (element.getKind() != ElementKind.CLASS) {
messager.printMessage(Diagnostic.Kind.ERROR, "@Activity should be on top of classes");
return false;
}
}
return true;
}
@Override
public Set<String> getSupportedAnnotationTypes() {
return Collections.singleton(Disable.class.getCanonicalName());
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
}
我正在使用InteliJ IDEA,并且在设置中启用了注释处理器。 注释处理器类可能看起来很愚蠢,我真的想让它运行,然后我将改进它的功能。
编辑: 有“示例”模块的build.gradle
plugins {
id 'java'
}
group 'sk.runner'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
implementation project(":core")
annotationProcessor project(":annotation-processors")
}
答案 0 :(得分:1)
应该使用gradle完全配置构建过程,而不是使用Intellij IDEA。这样,它将独立于IDE,并且IDEA支持与gradle项目自动同步。
在gradle中,您可以尝试这样的操作,然后运行gradle的“ build”任务(或“ classes”任务以仅编译源代码):
task myCustomAnnotationProcessorTask(type: JavaCompile, group: 'build') {
source = sourceSets.main.java
classpath = sourceSets.main.compileClasspath
options.compilerArgs = ['-proc:only',
'-processor', 'jacore.processors.Processor']
}
compileJava.dependsOn myCustomAnnotationProcessorTask