gradle - 接口 org.gradle.api.Action 是如何工作的?

gao*_*olf 5 android gradle

我正在尝试了解 android 插件,当我查看“defaultConfig”时,我发现该方法是

public void defaultConfig(Action<ProductFlavor> action) {
    this.checkWritability();
    action.execute(this.defaultConfig);
}
Run Code Online (Sandbox Code Playgroud)

并调用 action.execute(this.defaultConfit) 调用针对 this.defaultConfig 的闭包。

这令人困惑,所以我查看了接口 Action 的文档,看看它有什么魔力。

根据Action接口的文档,在调用action.execute(obj)时,实际上是“对给定的对象执行这个动作”,这里的给定对象是obj。

这是如何运作的?

ASAIK,如果我想针对 obj 调用一个方法,我使用“it”来引用 obj: it.doSth(),否则将针对“this”调用该方法。

但是当使用 Action 接口时,“it”就不再需要了,这个接口内的方法调用只会针对“it”调用。

我还写了一些代码来测试它:

class Main {
        Test test = new Test()
        test.actionReceiver {
//            actionName "test ok"
            it.actionName "test ok"

        }

    }

    static interface MyAction<T> {
        void execute(T)
    }

    static class MyActionReceiver {
        void actionName(String name) {
            println name
        }
    }

    static class Test {
        MyActionReceiver actionReceiver = new MyActionReceiver()

        void actionReceiver(MyAction<MyActionReceiver> action) {
            action.execute(actionReceiver)
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

如果我的界面MyAction具有 Action 界面所具有的魔力,那么调用不带“它”的 actionName 应该可以正常工作,但事实并非如此。

我的问题是:Action 界面如何工作以及如何让我的界面以相同的方式工作?

and*_*dev 1

Gradle 任务可以包含一个或多个操作。您可以在此处找到有关操作的更多信息: https://docs.gradle.org/current/javadoc/org/gradle/api/Action.html#execute(T) 操作通常在

首先执行{...}

或者

做最后{...}

任务定义的块。看:

task hello {
    doLast {
        println 'Hello world!'
    }
}
Run Code Online (Sandbox Code Playgroud)

编写自定义任务时,您可以简单地使用@TaskAction注释来注释您的主要操作:

task hello(type: GreetingTask)

class GreetingTask extends DefaultTask {
    @TaskAction
    def greet() {
         println 'hello from GreetingTask'
     }
}
Run Code Online (Sandbox Code Playgroud)

一些更有用的链接:

https://docs.gradle.org/current/userguide/tutorial_using_tasks.html https://docs.gradle.org/current/javadoc/org/gradle/api/Task.html

  • 请注意,问题根本不是关于任务,而是关于编写 Gradle DSL 中使用的“Action&lt;T&gt;”接口。 (3认同)