【问题标题】:How to provide the value of a @Nested property of a gradle task?如何提供 gradle 任务的 @Nested 属性的值?
【发布时间】:2021-06-10 02:21:06
【问题描述】:

gradle 文档描述了自定义 gradle 任务的 @Nested 注释: https://docs.gradle.org/current/userguide/more_about_tasks.html#sec:task_input_output_annotations

不幸的是,没有关于如何在build.gradle 文件中使用这种机制的完整示例。我创建了一个项目来演示 gradle 配置项目时发生的一个奇怪的异常: https://github.com/NicolasRouquette/gradle-nested-property-test

build.gradle 有以下内容:

task T(type: NestedTest) {
    tool = file('x')
    metadata = {
        a = "1"
    }
}

NestedTest 自定义任务位于 buildSrc 文件夹中:

class NestedTest extends DefaultTask {

    @InputFile
    public File tool

    @Nested
    @Input
    public Metadata metadata

    @TaskAction
    def run() throws IOException {
        // do something...
    }
}

重要的是 @Nested 属性,它的类型非常基本:

class Metadata {
    String a
}

当我执行以下命令时:./gradlew tasks,我得到了这个:

Build file '/opt/local/github.me/gradle-nested-property-test/build.gradle' line: 26

* What went wrong:
A problem occurred evaluating root project 'gradle-nested-property-test'.
> Cannot cast object 'build_6wy0cf8fn1e9nrlxf3vmxnl5z$_run_closure4$_closure5@2bde737' with class 'build_6wy0cf8fn1e9nrlxf3vmxnl5z$_run_closure4$_closure5' to class 'Metadata'

谁能解释发生了什么以及如何进行这项工作?

  • 尼古拉斯

【问题讨论】:

    标签: gradle gradle-task


    【解决方案1】:

    查看Gradle源代码中的单元测试,我发现@Nested属性的语法需要调用build.gradle文件中的类型构造函数。

    也就是说,以下工作:

    task T(type: NestedTest) {
        tool = file('x')
        metadata = new Metadata(
            a: "1"
        )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-09
      • 1970-01-01
      • 1970-01-01
      • 2015-08-12
      相关资源
      最近更新 更多