How to set the JavaToolChain inside the apply method of Plugin?

I am using Gradle 6.8.1 and have all of my build logic inside a Plugin that I share among many projects. I am trying to take advantage of java toolchains but just can’t figure out the syntax for adding a toolchain inside the apply(Project project) method of a Plugin. I have tried a few different things and all of them result in Could not get unknown property 'JavaLanguageVersion' for object of type org.gradle.jvm.toolchain.internal.DefaultToolchainSpec. Generally going from build.gradle syntax to a Plugin just requires explicitly calling methods on project but that isn’t working in this case.

class FooPlugin implements Plugin<Project> {

   @Override
    void apply(Project project) {
        //This one is straight from the user guide except for the addition of "project."
         project.tasks.withType(JavaCompile).configureEach {
            javaCompiler = javaToolchains.compilerFor {
                languageVersion = JavaLanguageVersion.of(11)
            }
        }

        //Tried this one too, also results in same error
        project.java {
            toolchain {
                languageVersion = JavaLanguageVersion.of(11)
            }
        }

      //I have also tried setting it in a java compiler block I already have...results in same error
       project.tasks.withType(JavaCompile) { JavaCompile javaCompile ->
            javaCompile.javaCompiler = javaToolchains.compilerFor {
                languageVersion = JavaLanguageVersion.of(11)
            }
            javaCompile.options.deprecation = true
            javaCompile.options.incremental = true
            javaCompile.options.release.set(JAVA_RELEASE_VERSION)
        }

    }

}

Can anyone provide any insight to the proper syntax?

Sounds like you simply miss to import the JavaLanguageVersion class.

Indeed. Well that is embarrassing. I depend on my IDE too much which isn’t as helpful with dynamic languages like groovy. Really surprised IntelliJ didn’t auto-import that or at least offer to (it offered that option after pressing alt-enter though).

Yep, one of the reasons I never use Groovy DSL these days, but always use Kotlin DSL when I can. :slight_smile:

2 Likes