自从我开始使用Groovy以来已经过了几天。但是,通过所有的阅读和冲浪,我还无法弄清楚如何实现自己的想法。所以,请原谅我。一如既往地感谢您的帮助。

我要实现的目标是:我有一个Java类,例如ServiceClass,它具有一些方法(getMethod()postMethod()等)来发出一些REST GET / POST请求(单独运行就可以了)。现在,我想公开一个DSL,以便最终用户可以说以下内容:callService ServiceClass method getMethod并且我可以执行ServiceClass.getMethod()

到目前为止,我一直在尝试以下操作:我在某个位置放置了userCommand文件,该文件现在显示为:callService ServiceClass

我有一个sample.groovy就是现在做的:

class Sample {
    def srvc
    def callService(srvc) {
        this.srvc = srvc
        "Calling $srvc"
    }
}


我有一个integrator.groovy文件,该文件具有:

//necessary imports
class Integrator{
    def sample = new Sample()
    def binding = new Binding([
        sample:sample,
        ServiceClass: new ServiceClass(),
        callService:sample.&callService ])
    def shell = new GroovyShell(binding)

    def runIt() {
        shell.evaluate("userCommand")
    }
}


然后从我的Java应用程序运行它,我正在做:

public static void main(String[] args) {
    Integator i = new Integrator()
    i.runIt();
}


但这是行不通的。使用以上语法,它表示:


  线程“主”中的异常java.lang.NullPointerException:无法在空对象上调用方法setVariable()。


谁能告诉我如何传递参数并创建对象实例?

最佳答案

更新:考虑以下userCommand文件:

文件userCommand

callService ServiceClass getMethod


groovy将其解析为callService(ServiceClass).getGetMethod()。因此,您需要一个getProperty方法,将调用重新路由到正确的方法:

文件Dsl.groovy

class Dsl {
  static void main(args) {
      new Integrator().runIt()
  }
}

class DslDelegate {
    def service
    def callService(service) {
        this.service = service
        this
    }

    def getProperty(String prop) {
      if (prop == "getMethod") { service.getMethod() }
      else { throw new RuntimeException("Unrecognized property '$prop'") }
    }
}

class ServiceClass {
  def getMethod() { "serviceClass getMethod" }
}

class Integrator{
    def dslDelegate = new DslDelegate()
    def binding = new Binding([
        ServiceClass: new ServiceClass(),
        callService:dslDelegate.&callService ])
    def shell = new GroovyShell(binding)

    def runIt() {
        assert shell.evaluate(new File("userCommand")) ==
            "serviceClass getMethod"
    }
}


注意我重命名了Sample类,因此它成为ServiceClass的委托人。现在,它将DSL /服务职责分开。

您也可以执行callService ServiceClass method getMethod,但是它需要更多代码。

09-27 09:04