【问题标题】:Nested object inside custom plugin extension自定义插件扩展中的嵌套对象
【发布时间】:2015-11-09 10:16:33
【问题描述】:

我正在开发一个自定义 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()'

如何在 MyPluginExtension 类中定义 property2 闭包?

编辑

我试过这个:

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

它无法解析嵌套的闭包字段。

【问题讨论】:

    标签: java gradle gradle-plugin


    【解决方案1】:

    您需要使用 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 实现的工作演示。

    【讨论】:

    • 谢谢。如果我使用 Java 而不是 Groovy 会怎样?
    • 只需使用 java 语法定义它。应该也可以。
    • 谢谢。我已经尝试过了,似乎已经解决了,但现在它无法解析嵌套的闭包字段。看看我的编辑。
    • 看我的回答,我的代码中有一个叫a1的方法。
    • @bigdestroyer,需要添加:void a1(String a1) { this.a1 = a1; }方法。
    猜你喜欢
    • 1970-01-01
    • 2021-02-19
    • 2012-09-28
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    相关资源
    最近更新 更多