问题描述
以下两个代码片段有什么区别?
第一:
任务copyFiles(类型:复制)<< {
fromfolder / from
intodest / folder
}
第二:
任务copyFiles(类型:复制){
fromfolder / from
到dest / folder
}
简而言之,第一个代码段出错了,第二个代码段是正确的。
Gradle构建分三个阶段进行:初始化,配置,和执行。像从
和到
配置任务的方法,因此需要在配置阶段。但是,<<
(这是 doLast
的快捷方式)添加了任务操作 - 它指示任务如果和在执行时执行什么操作。换句话说,第一个代码片段在执行阶段配置了任务,甚至更糟糕的是,在其主(复制)操作之后执行了它。因此,配置不会有任何影响。
通常,任务是或类型(已经带来任务操作)或 a <<
(用于特设任务)。有两种方法合理的用例(在任务的主要工作之后做了一些自定义工作),但更常见的是,这不是任务配置得太迟的错误。
我通常建议使用 doLast
而不是 <<<$ code>,因为它的含义较少,更容易发现这些错误。 (一旦理解了这些概念,很明显,
任务copyFiles(type:Copy){doLast {from ...}}
是错误的。)
What's the difference between the following two code snippets?
First:
task copyFiles(type: Copy) << {
from "folder/from"
into "dest/folder"
}
Second:
task copyFiles(type: Copy) {
from "folder/from"
into "dest/folder"
}
In short, the first snippet is getting it wrong, and the second one is getting it right.
A Gradle build proceeds in three phases: initialization, configuration, and execution. Methods like from
and into
configure a task, hence they need to be invoked in the configuration phase. However, <<
(which is a shortcut for doLast
) adds a task action - it instructs the task what to do if and when it gets executed. In other words, the first snippet configures the task in the execution phase, and even worse, after its main (copy) action has been executed. Hence the configuration won't have any effect.
Typically, a task has either a type (which already brings along a task action) or a <<
(for an ad-hoc task). There are legitimate uses cases for having both (doing a bit of custom work after the task's "main" work), but more often that not, it's a mistake where the task gets configured too late.
I generally recommend to use doLast
instead of <<
, because it's less cryptic and makes it easier to spot such mistakes. (Once you understand the concepts, it's kind of obvious that task copyFiles(type: Copy) { doLast { from ... } }
is wrong.)
这篇关于Gradle任务差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!