Change output directory of generated code in gradle

廉价感情. 提交于 2019-12-06 19:33:19

问题


Project contains annotation processor which generates java code during compilation. By default, gradle outputs generated source files into build/classes directory. That causes some problems with discovery of newly generated source files by IntelliJ.

Is there any straightforward way of configuring gradle to output source files into another directory? For example $buildDir/gen/main/java or $buildDir/build/generated/main/java?


回答1:


There is an option for java compiler which allows to customize output directory for generated java sources (documentation).

-s dir

Specify the directory where to place generated source files. The directory must already exist; javac will not create it. If a class is part of a package, the compiler puts the source file in a subdirectory reflecting the package name, 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.

Example of build.gradle

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"
        }
    }
}

This code snippet does next:

  • creates and specifies directory as output for generated code
  • deletes generated sources if clean task is invoked
  • adds new source set

Update

Use gradle apt plugin instead.




回答2:


Simply specify value for project.buildDir property in your build.gradle file:

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

This will put all generated build files to the <project_root>/gen/main/java folder.




回答3:


By default generated Java files are under $generatedFilesBaseDir/$sourceSet/$builtinPluginName, where $generatedFilesBaseDir is $buildDir/generated/source/proto by default, and is configurable. E.g.,

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

The subdirectory name, which is by default $builtinPluginName, can also be changed by setting the outputSubDir property in the builtins or plugins block of a task configuration within generateProtoTasks block (see previous section). E.g.,

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

to see github protobuf-gradle-plugin



来源:https://stackoverflow.com/questions/37512772/change-output-directory-of-generated-code-in-gradle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!