How to add JARs generated by tasks to compile dependencies

I have an Android app that depends on a library in the same tree, that itself depends on a set of JARs that need to be built in a separate source tree (using Ant) and then copied into a project. Here is the relevant subset of what I currently have:

apply plugin: 'com.android.library'

dependencies {
    compile fileTree('libs') {
        include '*.jar'
        builtBy 'buildJars'
    }
}

task buildJars(type: Exec) {
    outputs.dir('libs')
    commandLine 'ant' 'buildJars'
}

clean.dependsOn cleanBuildJars

clean << {
    exec {
        commandLine 'ant' 'clean'
    }
}

The first time I run ./gradlew assembleDebug (after a ./gradlew clean) I get the following error:

:app:preBuild
[snip - other Gradle tasks]
:lib:buildJars
[snip - Ant output]
BUILD SUCCESSFUL
Total time: 0 seconds
:lib:preBuild UP-TO-DATE
[snip - other Gradle tasks]
:lib:compileReleaseJavaWithJavac
/path/to/file.java: error: cannot find symbol
[snip - more errors]
:lib:compileReleaseJavaWithJavac FAILED

The second time, it works fine:

:app:preBuild
[snip - other Gradle tasks]
:lib:buildJars UP-TO-DATE
:lib:preBuild UP-TO-DATE
[snip - other Gradle tasks]
:lib:compileReleaseJavaWithJavac
[snip - other Gradle tasks]

Obviously the second time the JARs are in the libs directory, and are being added to the javac classpath correctly. But how can I get them added correctly in the first instance? What do I need to have :lib:buildJars run before? No other Gradle task for the library is called before :lib:buildJars (according to the output at least)…

1 Like

I have tried using the method listed here, resulting in the following:

apply plugin: 'com.android.library'

task buildJars(type: Exec) {
    outputs.dir('libs')
    commandLine 'ant' 'buildJars'
}

dependencies {
    compile fileTree(tasks.buildJars.outputs.files.singleFile) {
        builtBy tasks.buildJars
        include '**/*.jar'
    }
}

clean << {
    exec {
        commandLine 'ant' 'clean'
    }
}

It behaves exactly as before - fails the first time, succeeds the second. I think that makes sense, because the only real difference is in the enumeration of the JARs.