问题
I am trying to make annotation processor in plain java (not android api), but anytime I run my main function, processor is supposed to stop build process because of error, but it doesn't.
My project structure is:
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)
Annotation processor class is
@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();
}
}
I am using InteliJ IDEA and annotation processors are enabled in settings. Annotation processor class may seem stupid, I really want to make it run, then I will improve features of it.
Edit: There is build.gradle of 'example' module
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")
}
回答1:
Instead of using Intellij IDEA, you should configure your build process entirely in gradle. This way it will be IDE-independent, and IDEA supports auto-sync with the gradle project.
In gradle you can try something like this, and then run the gradle 'build' task (or 'classes' task to only compile source):
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
来源:https://stackoverflow.com/questions/52746233/annotation-processor-doesnt-run-in-plain-java