代码之家  ›  专栏  ›  技术社区  ›  Martin

注释处理器不能在纯Java中运行

  •  1
  • Martin  · 技术社区  · 6 年前

    我的项目结构是:

    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,并且在设置中启用了注释处理器。 注释处理器类可能看起来很愚蠢,我真的想让它运行,然后我会改进它的功能。

    编辑:

    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 回复  |  直到 6 年前
        1
  •  1
  •   cdalxndr    6 年前

    您应该完全在gradle中配置构建过程,而不是使用Intellij IDEA。这样它将独立于IDE,IDEA支持与gradle项目自动同步。

    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