本文介绍了在gradle的插件扩展中传递闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过闭包作为插件的配置.这是它的最小版本:

I'd like to pass a closure as configuration for a plugin. Here is a minimal version of it:

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")
  }
}

这是行不通的,永远不会对闭包进行评估(无论是在配置时还是在我打算进行闭包时,都是如此:

This doesn't work, the closure is never evaluated (nor at configuration nor when I intend it to:

$ ./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如何评估扩展内容的信息.是否可以通过扩展以某种方式传递某些东西并在插件的任务中对其进行评估?

I think I am missing something about how gradle evaluates the contents of the extensions. Is it possible to somehow pass something via an extension and evaluate it in a task in the plugin?

推荐答案

该解决方案令人惊讶地令人印象深刻.将用于调用闭包的行更改为:

The solution is surprisingly unimpressive. Change the line for calling the closure to:

project.extensions.testConfig.closure.call()

注意使用 .call()与仅调用()

还注意到这调用了闭包:

Also noticed that this calls the closure:

println "Trying to run closure ${project.extensions.testConfig.closure}"

为什么?

这篇关于在gradle的插件扩展中传递闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 15:50