Conditional Toolchain Enforcement

I have a multi-module project in which one module is Java 17, and the other module is Java 8. The Java 17 module depends on the Java 8 module.

project
 module-1
  build.gradle.kts -> java 17 toolchain
 module-2
  build.gradle.kts -> java 8 toolchain

module-1’s build.gradle.kts

dependencies {
  implementation(project(":module-2"))
}

If I build module-1 on an Java 17 docker image, the build will fail because no Java 8 toolchain is available to build module-2. How can I allow the Java 17 toolchain to be used when building module-2 as a dependency of module-1, but require the Java 8 toolchain when building module-2 directly?

I’m wondering if setting a system or environment variable would be the best? Or is there a better approach?

./gradlew -Pjava17=true :module-1:assemble

java {
    if (!project.hasProperty("java17")) {
        toolchain {
            languageVersion = JavaLanguageVersion.of(8)
        }
    }
}

Why should you do that?
Just apply the foojay resolver convention plugin, so that the needed Java 8 can be auto-provisioned, then the build works everywhere internet is available.

Because for the Java 17 module it is fine if module-2 is compile with Java 17. Adding the foojay resolver will work, but then every build that extra toolchain needs to be downloaded which adds unnecessary time and network activity to the build

Yeah, well, if you want it like that, checking a project property is maybe the way to go.
You might though consider setting the toolchain language version depending on the property, not leaving out the whole configuration.
But well, as long as you ensure you are running Gradle with Java 17 it shouldn’t make much difference.

But maybe re-think your check logic. -Pjava17=false would currently also do the Java 17 build as you just check for presence of the property, not its value.

Yep, I was just simplifying the logic to make the approach clearer. Thanks for your help!

1 Like

You could probably also set the toolchain to 17 for B always and set release on the compile task to 8.

That’s not a bad idea, but unfortunately we have a more complex build system that doesn’t directly use that task. I’m going to go with the project property approach

1 Like