代码之家  ›  专栏  ›  技术社区  ›  madhead

在Gradle Kotlin DSL中注册和创建有什么区别

  •  2
  • madhead  · 技术社区  · 7 年前

    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,那么有什么区别呢?

    2 回复  |  直到 7 年前
        1
  •  14
  •   M.Ricciuti    7 年前

    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 在Gradle 5.0之前的版本中)与 Task Configuration Avoidance 新的API,详细介绍了它 here (见 this section ):

    如何延迟任务创建?

        2
  •  6
  •   madhead    7 年前

    被接受的答案很好,但我想补充一点,如果您想实际使用 created / registering 稍后调用,则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()
    
    推荐文章