Change output directory of generated code in gradle

前端 未结 3 954
名媛妹妹
名媛妹妹 2021-02-19 03:32

Project contains annotation processor which generates java code during compilation. By default, gradle outputs generated source files into build/classes directory.

3条回答
  •  后悔当初
    2021-02-19 03:59

    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.

提交回复
热议问题