Sunday, August 4, 2019

Compiling one additional file with an Android Gradle JavaCompile task

I recently needed to create a Gradle task to compile a single Java file in an Android project after the normal compilation of a variant's source set was complete. I found some inspiration from this Gradle forum thread, but things are more complicated when using the Android Gradle plugin rather than the plain Java one. I'm not sure how to get the appropriate paths from the project configuration, so I grab them from an existing Java compile task for the variant. task is the new JavaCompile task; javaTask is the existing one for the variant (e.g. compileDebugUnitTestJavaWithJavac):
task.options.sourcepath = project.fileTree("src/test/java")
task.source = task.options.sourcepath!!.asFileTree
task.include("com/example/package/TheFile.java")
task.classpath = javaTask.classpath + javaTask.outputs.files
task.options.bootstrapClasspath = javaTask.options.bootstrapClasspath
task.destinationDir = javaTask.destinationDir
task.sourceCompatibility = javaTask.sourceCompatibility
task.targetCompatibility = javaTask.targetCompatibility

(That's Kotlin code; Groovy will probably be similar minus the !!.) The file can be excluded from the original compilation task's inputs like so:

javaTask.excludes.add("com/example/package/TheFile.java")

No comments:

Post a Comment