You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写Gradle插件遇“无法设置只读属性”错误求助

Gradle DSL 配置报错排查

我想要实现如下Gradle DSL配置:

toolSetups {
    someTool {
        argsFile = file('run/some_tool/xrun_files.f')
    }
    someOtherTool {
        argsFile = file('run/some_other_tool/xrun_files.f')
    }
}

我通过向项目添加包含ToolSetup条目的扩展来实现该功能:

extensions.add('toolSetups', project.container(ToolSetup))

最初按照用户指南示例,我在ToolSetup接口中声明argsFile属性:

interface ToolSetup {
    Property<File> getArgsFile()
}

之后查询得知ToolSetup需要具备name属性,于是将其重构为抽象类:

abstract class ToolSetup {
    private final String name
    
    public ToolSetup(String name) {
        this.name = name
    }

    String getName() {
        return name
    }

    abstract Property<File> getArgsFile()
}

此时触发错误:

Cannot set the value of read-only property 'argsFile' for object of type ToolSetup$Inject.

我尝试过显式调用argsFile.set(file(...)),也用ObjectFactory创建Property实例,但都会触发相同错误。此前用Java编写的同类插件可正常运行,推测是Groovy与Gradle自动实现相关的细节问题,恳请指出问题所在。

以下是可复现该问题的完整build.gradle文件:

abstract class ToolSetup {
    private final String name
    
    public ToolSetup(String name) {
        this.name = name
    }

    String getName() {
        return name
    }

    abstract Property<File> getArgsFile()
}

extensions.add('toolSetups', project.container(ToolSetup))

toolSetups {
    someTool {
        argsFile = file('run/some_tool/xrun_files.f')
    }
    someOtherTool {
        argsFile = file('run/some_other_tool/xrun_files.f')
    }
}

内容的提问来源于stack exchange,提问作者Tudor Timi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 20:55:58