'How to configure Gradle Java plugin from a custom Gradle plugin
I've written a custom Gradle plugin in Kotlin 1.2.50 for use with Gradle 4.8.
I've successfully applied the Java plugin from my plugin's apply method:
override fun apply(project: Project) {
project.pluginManager.apply(JavaPlugin::class.java)
// configure Java plugin here
}
How do I configure the Java plugin?
e.g., I want to achieve the equivalent of the following that would normally be in a build.gradle.kts
:
java {
sourceCompatibility = VERSION_1_10
targetCompatibility = VERSION_1_10
}
Solution 1:[1]
I dug through the Gradle code and found a solution:
override fun apply(project: Project) {
project.pluginManager.apply(JavaPlugin::class.java)
val javaPlugin = project.convention.getPlugin(JavaPluginConvention::class.java)
javaPlugin.sourceCompatibility = VERSION_1_10
javaPlugin.targetCompatibility = VERSION_1_10
}
Solution 2:[2]
I know this might be a bit late, but for anyone who seeks an answer to this question in 2022, the official guide shows how to configure plugins via extensions. Also, just for the sake of completeness, the guide recommends not to enforce the usage of certain plugins but instead to reactively configure them when they are available.
So today, the solution to your problem might either look like this (sorry for using Java code, although the code should be mappable to Kotlin straightforwardly):
// enforcing the Java plugin
project.getPluginManager().apply(JavaPlugin.class);
JavaPluginExtension javaPluginExtension = project.getExtensions().getByType(JavaPluginExtension.class);
javaPluginExtension.setSourceCompatibility(JavaVersion.VERSION_1_10);
javaPluginExtension.setTargetCompatibility(JavaVersion.VERSION_1_10);
or like this:
// reactively configuring the Java plugin
project.getPlugins().withType(JavaPlugin.class, javaPlugin -> {
JavaPluginExtension javaPluginExtension = project.getExtensions().getByType(JavaPluginExtension.class);
javaPluginExtension.setSourceCompatibility(JavaVersion.VERSION_1_10);
javaPluginExtension.setTargetCompatibility(JavaVersion.VERSION_1_10);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | XDR |
Solution 2 |