How to compile a single java file with gradle?

I tried to use @I Stevenson answer with gradle version 6.4.1. There were a couple of changes that surprised me so hopefully this helps someone else. Changes in this task are :

destinationDir-> destinationDirectory(incubating)(I also had issue with type)

compileOne.options.compilerArgs -> options.sourcepath this is also defined within task

I also needed to add annotation processing in my compilation because I am using project lombok. I understand that your question did not ask for annotation processing so I will make a comment in the task that states that this is extra.

apply plugin: 'java'
task compileOne (type: JavaCompile) {
    source = sourceSets.main.java.srcDirs
    include 'some/pkg/ClassTwo.java'
    classpath = sourceSets.main.compileClasspath
    destinationDirectory = new File("${buildDir}/classes/java/main") 
    options.sourcepath = sourceSets.main.java.getSourceDirectories()
    options.annotationProcessorPath = sourcesSet.main.compileClasspath//extra for lombok
}

Thanks to the discussion with @PeterNiederwieser on the original post in the comments, I'll provide the answer here for completeness.

To have gradle JavaCompile function in a manner very similar to the ant javac, you need to provide the sourcepath compiler option via the options.compilerArgs property. Therefore, the gradle script that now works is as follows:

apply plugin: 'java'

task compileOne (type: JavaCompile) {
    source = sourceSets.main.java.srcDirs
    include 'some/pkg/ClassTwo.java'
    classpath = sourceSets.main.compileClasspath
    destinationDir = sourceSets.main.output.classesDir
}

compileOne.options.compilerArgs = ["-sourcepath", "$projectDir/src/main/java"]

Note specifically the last line (the only difference) which allows all to work. The result of which is that it will actually compile both ClassOne and ClassTwo at build time - rather than only attempting the single explicit file you specified. Any other classes (that are not required) remain uncompiled - as confirmed by looking in the build directory.

Thanks Peter!

Tags:

Java

Gradle