Gradle扩展名为Closure的NamedDomainObjectContainer
我正在尝试构建一个Gradle插件,该插件将允许以下内容:Gradle扩展名为Closure的NamedDomainObjectContainer,gradle,gradle-plugin,Gradle,Gradle Plugin,我正在尝试构建一个Gradle插件,该插件将允许以下内容: myPluginConfig { something1 { // this is a closure } somethingElse { // this is another closure } // more closures here } 为了实现这一点,我非常确定我需要使用NamedDomainObjectContainer包装Closure集合,因此我设置
myPluginConfig {
something1 {
// this is a closure
}
somethingElse {
// this is another closure
}
// more closures here
}
为了实现这一点,我非常确定我需要使用NamedDomainObjectContainer
包装Closure
集合,因此我设置了以下插件:
class SwitchDependenciesPlugin implements Plugin<Project> {
void apply(Project project) {
// add the extension
project.getExtensions().myPluginConfig = project.container(Closure)
// read the current configuration
NamedDomainObjectContainer<Closure> config = project.myPluginConfig
// test it out, always returns []
System.out.println(config)
}
}
对于这个用例,我需要有
mypluginfig
的动态名称,因此需要一个Map
或namedMainObjectContainer
,您能详细说明您在这里尝试建模的内容吗?我想你有两个选择。一种是使用NamedDomainObjectContainer。这里需要一个表示“某物”的类。看看Gradle userguide中关于维护多个域对象的章节(请参阅),在userguide的示例中,“东西”是“书”。上面描述的内置配置语法是免费的
如果您希望使用如上所述的语法而不需要维护多个域对象,只需向扩展类添加一个将闭包作为参数的方法:
void somethingToConfigure(Closure) {
}
不能将
Closure
作为NamedDomainObjectContainer
的类型,因为您使用的类型必须具有名为name
的属性和带有单个字符串参数的公共构造函数
为了克服这个问题,您可以在
Closure
周围创建一个包装器,并添加一个name
字段。这个例子正是我想要实现的,只是我需要的不是Book
s,而是Closure
s,因为我需要将它们传递给project.dependencies
。这对Closure
不直接起作用,因为Closure没有实现命名的
接口,也没有名称
属性。那么我如何使它起作用呢?换句话说,Gradle是如何处理“依赖项”的?dependencies{}
在构建脚本中只是一个在项目上签名为“void dependencies(Closure)的方法。闭包将委托传递给DependencyHandler。你能分享一些关于你的用例的更多信息吗?我已经在最初的帖子中指定了这个用例。
void somethingToConfigure(Closure) {
}