javagradlegradle-plugin

How do I configure an Action in a gradle plugin from inside a custom Java plugin


From inside a gradle plugin I want to configure another gradle plugin. Especially I want to set the java toolchain like mentioned in the gradle manual

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}

I can acces the extension with the PluginManager:

package com.clavisit.clientis.web.gradle;

import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.plugins.JavaPluginExtension;

public class BuildPlugin implements Plugin<Project> {

  @Override
  public void apply(Project target) {
    target.getPluginManager().apply("java");

    target.getExtensions().configure(JavaPluginExtension.class, javaPluginExtension -> {
      // how to configure the toolchain
    });
  }

}

But how do I configure the toolchain here? The Extensions offers me a getter and an Action method, but no way to configure a JavaToolChainSpec.

  JavaToolchainSpec getToolchain();

  JavaToolchainSpec toolchain(Action<? super JavaToolchainSpec> action);

Any ideas?


Solution

  • You've done all the hard work, and shown how to configure an object using an Action already. Just keep going, using those lambda functions to configure:

    target.getExtensions().configure(JavaPluginExtension.class, javaPluginExtension -> {
        javaPluginExtension.toolchain(toolchain -> { 
            toolchain.getLanguageVersion().set(JavaLanguageVersion.of(21)); 
        });
    });
    

    Perhaps the other tricky bit is getLanguageVersion returns a Property object, so you need to set it, rather than doing an assignment as you are permitted to in a build script.