我想传递一个闭包作为插件的配置。这是它的最小版本:
package org.samuel.gradle.plugins
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
class TestPlugin implements Plugin<Project> {
void apply(Project project) {
project.extensions.create("testConfig", TestConfig)
Task test = project.task("testTask") {
doFirst {
println "The message is already " + project.extensions.testConfig.message
println "Trying to run closure " + project.extensions.testConfig.closure
project.extensions.testConfig.closure()
println "did it run?"
}
}
}
}
class TestConfig {
String message = "Testing ..."
Closure closure = {
println("running closure")
}
}
这不起作用,关闭永远不会被评估(也不是在配置时,也不是我打算:
$ ./gradlew test
:buildSrc:compileJava UP-TO-DATE
:buildSrc:compileGroovy
:buildSrc:processResources UP-TO-DATE
:buildSrc:classes
:buildSrc:jar
:buildSrc:assemble
:buildSrc:compileTestJava UP-TO-DATE
:buildSrc:compileTestGroovy UP-TO-DATE
:buildSrc:processTestResources UP-TO-DATE
:buildSrc:testClasses UP-TO-DATE
:buildSrc:test UP-TO-DATE
:buildSrc:check UP-TO-DATE
:buildSrc:build
:testTask
The message is already Testing ...
Trying to run closure org.samuel.gradle.plugins.TestConfig$_closure1@5600ea3b
did it run?
BUILD SUCCESSFUL
Total time: 1.569 secs
我认为我遗漏了一些关于gradle如何评估扩展内容的内容。是否有可能通过扩展程序以某种方式传递某些内容并在插件中的任务中对其进行评估?
答案 0 :(得分:1)
该解决方案令人惊讶地令人印象深刻。将用于调用闭包的行更改为:
project.extensions.testConfig.closure.call()
注意使用.call()
与仅调用()
还注意到这称为闭包:
println "Trying to run closure ${project.extensions.testConfig.closure}"