Change the output directory of the generated code in gradle

The project contains an annotation handler that generates Java code at compile time. By default, gradle outputs the source files to the build/classes directory. This causes some problems with detecting newly created source files using IntelliJ.

Is there an easy way to configure gradle to output source files to another directory? For example $buildDir/gen/main/java or $buildDir/build/generated/main/java ?

+8
source share
3 answers

There is an option for the java compiler, which allows you to configure the output directory for the generated java sources ( documentation ).

-s dir

Specify the directory for the source files. the directory must already exist; javac will not create it. If the class is part of a package, the compiler places the source file in a subdirectory reflecting the name of the package, creating directories as needed. For example, if you specify -s C: \ mysrc and the class is called com.mypackage.MyClass, then the source file will be placed in C:. \ Mysrc \ com \ MyPackage \ MyClass.java

build.gradle example

 compileJava { options.compilerArgs << "-s" options.compilerArgs << "$projectDir/generated/java" doFirst { // make sure that directory exists file(new File(projectDir, "/generated/java")).mkdirs() } } clean.doLast { // clean-up directory when necessary file(new File(projectDir, "/generated")).deleteDir() } sourceSets { generated { java { srcDir "$projectDir/generated/java" } } } 

The following code snippet:

  • creates and indicates the directory as a result for the generated code
  • deletes generated sources when calling a clean task.
  • adds a new source set

Update

Use the gradle apt plugin instead.

+10
source

Just specify the value for the project.buildDir property in the build.gradle file:

 project.buildDir = '/gen/main/java' 

This will place all generated assembly files in the <project_root>/gen/main/java folder.

+3
source

By default, the generated Java files are located in the $ generateFilesBaseDir / $ sourceSet / $ builtinPluginName directory, where $ generateFilesBaseDir is by default $ buildDir / generated / source / proto and is configured. For instance,

 protobuf { ... generatedFilesBaseDir = "$projectDir/src/generated" } 

The name of the subdirectory, which is $ builtinPluginName by default, can also be changed by setting the outputSubDir property in the unit of built-in or plug-in task configuration modules in the generateProtoTasks block (see the previous section). For instance,

 { task -> task.plugins { grpc { // Write the generated files under // "$generatedFilesBaseDir/$sourceSet/grpcjava" outputSubDir = 'grpcjava' } } } 

to see github protobuf-gradle-plugin

0
source

All Articles