2015-11-09 237 views
2

我正在開發一個定製的搖籃插件,我想定義的配置閉合(插件擴展名)是這樣的:嵌套對象

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); 

但在我的客戶項目,當我應用程式LY和配置如上所示的插件,我得到這個錯誤:

Gradle DSL method not found: 'property2()'

我如何定義我MyPluginExtensionproperty2關閉?

編輯

我已經試過這樣:

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 method not found: a1()

它無法解決嵌套封場。

回答

3

你需要利用與委託設置爲特定對象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 

也請看看here爲什麼需要額外的方法。和here你可以找到一個在java中實現的工作演示。

+0

謝謝。如果我使用Java而不是Groovy,那麼呢? –

+0

只需使用java語法定義它。也應該工作。 – Opal

+0

謝謝。我試過了,似乎解決了,但現在它不能解決嵌套閉包字段。看看我的編輯。 –