Gradle复制任务:为什么可以调用"into"方法的配置闭包调用"from"方法?
Gradle Copy task: Why can "from" method be called with configuration closure that can call "into" method?
考虑 gradle 文档中的以下示例(稍微简化):
task initConfig(type: Copy) {
from('src/main/config') {
include '**/*.properties'
include '**/*.xml'
filter(ReplaceTokens, tokens: [version: '2.3.1'])
}
}
此处,“from”方法在 AbstractCopyTask class 中声明,具有以下签名:
public AbstractCopyTask from(Object sourcePath, Closure c)
其中 c - 用于配置子 CopySourceSpec 的闭包。 CopySourceSpec 是一个仅声明“来自”方法的接口。
问题:如果上例中的闭包是通过仅允许调用“from”方法的子 CopySourceSpec 的文档配置闭包,为什么允许调用“include”和“filter”方法?
include
就是coming fromAbstractCopyTask
parent
例如,您可以在 groovy:
中执行此操作
class FromSpec {
String who
FromSpec(String who) {
this.who = who
}
def capitalize() {
who = who.capitalize()
}
}
class Testing {
FromSpec spec
def sayHello() {
println "Hello $spec.who"
}
def from(String who, Closure c) {
this.spec = new FromSpec(who)
c.delegate = this.spec
c.call()
}
def run(Closure c) {
c.delegate = this
c.call()
}
}
通过使用 Closure 委托,我们可以做到这一点
new Testing().run {
from('peshi') {
capitalize() // A method in the FromSpec
sayHello() // A method in the owner Testing class
}
}
然后我们得到输出
Hello Peshi
考虑 gradle 文档中的以下示例(稍微简化):
task initConfig(type: Copy) {
from('src/main/config') {
include '**/*.properties'
include '**/*.xml'
filter(ReplaceTokens, tokens: [version: '2.3.1'])
}
}
此处,“from”方法在 AbstractCopyTask class 中声明,具有以下签名:
public AbstractCopyTask from(Object sourcePath, Closure c)
其中 c - 用于配置子 CopySourceSpec 的闭包。 CopySourceSpec 是一个仅声明“来自”方法的接口。
问题:如果上例中的闭包是通过仅允许调用“from”方法的子 CopySourceSpec 的文档配置闭包,为什么允许调用“include”和“filter”方法?
include
就是coming fromAbstractCopyTask
parent
例如,您可以在 groovy:
中执行此操作class FromSpec {
String who
FromSpec(String who) {
this.who = who
}
def capitalize() {
who = who.capitalize()
}
}
class Testing {
FromSpec spec
def sayHello() {
println "Hello $spec.who"
}
def from(String who, Closure c) {
this.spec = new FromSpec(who)
c.delegate = this.spec
c.call()
}
def run(Closure c) {
c.delegate = this
c.call()
}
}
通过使用 Closure 委托,我们可以做到这一点
new Testing().run {
from('peshi') {
capitalize() // A method in the FromSpec
sayHello() // A method in the owner Testing class
}
}
然后我们得到输出
Hello Peshi