我正在开发一个自定义的Gradle插件,我想像这样定义一个配置闭包(插件扩展):
myplugin {
property1 'value'
property2 {
a1 'hello'
a2 'bye'
}
}
我有这个课程:
public class MyPluginExtension { //root extension
String property1;
Property2 peroperty2;
//getters and setters
}
public class Property2 {
String a1;
String a2;
//getters and setters
}
而且,在插件项目中,我以这种方式创建扩展:
project.getExtensions().create("myplugin", MyPluginExtension.class);
但是在我的客户端项目中,当我如上所示应用和配置插件时,我收到此错误:
未找到Gradle DSL方法:'property2()'
如何在property2
课程中定义MyPluginExtension
闭包?
修改
我试过这个:
public class MyPluginExtension { //root extension
String property1;
Property2 peroperty2;
//getters and setters
public void property2(Closure c) {
c.setResolveStrategy(Closure.DELEGATE_FIRST);
c.setDelegate(property2);
c.call();
}
}
但现在我收到了这个错误:
未找到Gradle DSL方法:a1()
它无法解析嵌套的闭包字段。
答案 0 :(得分:5)
您需要将Closure
与委托设置为特定对象:
class SamplePlugin implements Plugin {
void apply(Object p) {
p.extensions.create("e", MyPluginExtension)
}
}
class MyPluginExtension {
Property2 property2 = new Property2()
String property1
def property2(Closure c) {
c.resolveStrategy = Closure.DELEGATE_FIRST
c.delegate = property2
c()
}
}
class Property2 {
String a1
String a2
def a1(a1) {
this.a1 = a1
}
def a2(a2) {
this.a2 = a2
}
}
apply plugin: SamplePlugin
e {
property1 'lol'
property2 {
a1 'lol2'
a2 'lol3'
}
}
println e.property1
println e.property2.a1