Custom JavaCompile task with library dependencies

I have a custom JavaCompile task to work on pre-processed (obfuscation etc.) java source files. First I copy the sources (including my own dependencies) in one place and then compile to make a fat jar with this step.

task compileSources(type: JavaCompile) {
    dependsOn copySources
    def sources = copySources.outputDirectory

    source = file(sources)
    destinationDir = file(sources)
    classpath = files(sources)
    options.sourcepath = files(sources)

    outputs.dir(destinationDir)
}

When I add an external dependency (org.json) it fails.

task compileSources(type: JavaCompile) {
    // something like this does not work
    dependencies {
        compile 'org.json:json'
    }

    ...
    
}

How do I configure JavaCompile task to compile a source code set with external dependencies?

You didn’t add json to the task.

task compileSources(type: JavaCompile) {
    dependencies {
        compile 'org.json:json'
    }
}

is actually the same as

dependencies {
    compile 'org.json:json'
}
task compileSources(type: JavaCompile) {
}

as there is no dependencies method on the JavaCompile task.

The next point is, that the compile configuration is deprecated since years, you should for example use implementation instead.

You need to add your external dependencies to the classpath property to have them on the class path during compilation. You want to add configurations.compileClasspath.

1 Like

I did this

configurations {
    jsonlib
}
dependencies {
    jsonlib 'org.json:json:20171018'
}

task compileSources(type: JavaCompile) {
    dependsOn copySources
    def sources = copySources.outputDirectory

    source = file(sources)
    destinationDir = file(sources)
    classpath = files(sources, configurations.json) // <--- added configurations.json
    // classpath = files(sources, "path/to/jar/file") // can also do this
    options.sourcepath = files(sources)

    outputs.dir(destinationDir)
}

// to run from custom source set
run {
    if (usingCustomSource) {
         classpath = files(compileSources.destinationDir, configurations.json)
    }
}