我想在existant类型中添加一个函数,在我的例子中,这是NativeLibrarySpec
。
我尝试使用gradle extensions并且它已经完成了工作但现在我想将其概括为能够使用它,就好像它是NativeLibrarySpec
的DSL的标准功能一样。
问题是我只能在配置后(包含我的函数的块)访问实例,因此它失败了,因为它试图在我能够链接它之前调用specialConfig
...
以下是代码(不关心此示例适用于本机软件C ++):
// File: build.gradle
apply plugin: 'cpp'
class SpecialConfig {
NativeComponentSpec componentSpec
SpecialConfig(NativeComponentSpec componentSpec) {
this.componentSpec = componentSpec
}
def something(boolean enabled) {
componentSpec.sources {
cpp {
// Some important stuffs
}
}
}
}
model {
components {
main(NativeLibrarySpec) {
// How to bring this out ??
project.extensions.create('specialConfig', SpecialConfig, it)
// This is the new functionality I want to use
specialConfig {
something(true)
}
}
}
}
这是另一个例子,但它只适用于项目。* https://dzone.com/articles/gradle-goodness-extending-dsl
答案 0 :(得分:0)
请你试试吗
Movie
输出:
plugins {
id 'cpp'
}
class SpecialConfig {
// no need to pass this to the constructor we can just make it a
// method arg instead
SpecialConfig() {
}
// manipulate spec as desired
def something(NativeComponentSpec spec, boolean enabled) {
println "Hello something!"
spec.sources {
cpp {
// Some important stuffs
}
}
}
}
// add your extension earlier
project.extensions.create('specialConfig', SpecialConfig)
model {
components {
main(NativeLibrarySpec) { mySpec ->
// we can call our extension via the project
project.specialConfig { config ->
// our closure is handed an instance of the class
// on that we can call methods
config.something(mySpec, true)
}
// or more simply we could make it a one liner
project.specialConfig.something(mySpec, true)
}
}
}