mad*_*ead 6 gradle kotlin gradle-kotlin-dsl
在Gradle(5.0+)中有两种创建方法,即任务:
tasks {
    val javadocJar by creating(Jar::class) {
        val javadoc by tasks
        from(javadoc)
        classifier = "javadoc"
    }
}
和
tasks {
    val javadocJar by registering(Jar::class) {
        val javadoc by tasks
        from(javadoc)
        classifier = "javadoc"
    }
}
基本上是相同的API,有什么区别?
参见https://docs.gradle.org/current/userguide/kotlin_dsl.html#using_the_container_api:
tasks.named("check")                  
tasks.register("myTask1")
上面的示例依赖于配置避免API。如果您需要或希望热切地配置或注册容器元素,只需将named()替换为getByName()并将register()替换为create()。
之间的区别creating和registering(或create和register在摇篮之前的版本5.0)是关系到Task Configuration Avoidance新的API,这是在细节exaplined 这里(见本节:)
如何推迟任务创建?
该功能要求构建作者选择加入,方法是将任务创建从TaskContainer.create(java.lang.String)API迁移到TaskContainer.register(java.lang.String)API。register(…?)API仅在需要时才注册要在以后创建的任务。当调用create(…?)API时,它会继续急切地创建和配置任务。
接受的答案很好,但我想补充一点,如果您想稍后实际使用created/ registeringcall创建的引用,那么 API 将有所不同。相比
create<MavenPublication>("main") {
    …
    val sourcesJar by tasks.creating(Jar::class) {
        val sourceSets: SourceSetContainer by project
        from(sourceSets["main"].allJava)
        classifier = "sources"
    }
    artifact(sourcesJar)
}
和
create<MavenPublication>("main") {
    …
    val sourcesJar by tasks.registering(Jar::class) {
        val sourceSets: SourceSetContainer by project
        from(sourceSets["main"].allJava)
        classifier = "sources"
    }
    artifact(sourcesJar.get())
}
在注册的情况下,因为它是懒惰的,你需要额外的.get()调用,否则你会得到一个异常:
* What went wrong:
Cannot convert the provided notation to an object of type MavenArtifact: task ':experiments:sourcesJar'.
The following types/formats are supported:
  - Instances of MavenArtifact.
  - Instances of AbstractArchiveTask, for example jar.
  - Instances of PublishArtifact
  - Maps containing a 'source' entry, for example [source: '/path/to/file', extension: 'zip'].
  - Anything that can be converted to a file, as per Project.file()
| 归档时间: | 
 | 
| 查看次数: | 868 次 | 
| 最近记录: |