42

一种)

task build << {  
  description = "Build task."  
  ant.echo('build')  
}

二)

task build {  
  description = "Build task."  
  ant.echo('build')  
}

我注意到对于类型 B,任务中的代码似乎在键入时执行gradle -t- 即使只是列出所有各种可用任务,ant 也会回显“构建”。描述实际上也用类型 B 显示。但是,使用类型 A 列出可用任务时不执行任何代码,执行时不显示描述gradle -t。文档似乎没有涉及这两种语法(我发现)之间的区别,只是您可以以任何一种方式定义任务。

4

1 回答 1

56

第一种语法定义了一个任务,并提供了一些在任务执行时要执行的代码。第二种语法定义了一个任务,并提供了一些可以立即执行的代码来配置任务。例如:

task build << { println 'this executes when build task is executed' }
task build { println 'this executes when the build script is executed' }

实际上,第一种语法等价于:

task build { doLast { println 'this executes when build task is executed' } }

因此,在上面的示例中,对于语法 A,描述不会显示在 gradle -t 中,因为设置描述的代码在任务执行之前不会执行,而在运行 gradle -t 时不会发生这种情况。

对于语法 B,每次调用 gradle 都会运行执行 ant.echo() 的代码,包括 gradle -t

要提供要执行的操作和任务描述,您可以执行以下任一操作:

task build(description: 'some description') << { some code }
task build { description = 'some description'; doLast { some code } }
于 2010-05-05T05:12:18.877 回答