Search code examples
javamavengradleannotation-processing

Maven/Gradle set environment variable for compilation?


I developed an annotation processor that would optionally require the artifactId of the project to generate a file. I am using an environment variable (GRAPHDEP_USAGE) to get the value.

I can set the environment variable from shell before launching Maven/Gradle, but I would like the build tool to set the environment variable for me before the compilation instead:

  • For Maven, inside the pom.xml i would like to populate the environment variable GRAPHDEP_PROJECT with the content of ${artifactId}, before launching the compile goal.
  • For Gradle, inside the build.gradle i would like to populate the environment variable GRAPHDEP_PROJECT with the content of project.name, before launching the task compileJava.

I tried a few options without success. Any idea how i can do that?


Solution

  • Not exactly answering the question, but actually answering the question behind which was how to pass arguments to annotation processors.


    Compiler arguments can be specified with -A flag.

    In Gradle:

    compileJava.options.compilerArgs += "-Agraphdep.project=${project.name}"
    

    In Maven:

    <compilerArgs>
      <arg>-Agraphdep.project=${project.artifactId}</arg>
    </compilerArgs>
    

    Then from within an implementation of AbstractProcessor it is possible to retrieve the arguments using:

    processingEnv.getOptions().get("widget");
    

    The options supported must be declared by the processor, either by using the annotation @SupportedOptions({"widget"}) or by overriding the method public Set<String> getSupportedOptions().