【发布时间】:2014-12-05 11:39:04
【问题描述】:
自从我开始使用 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()....
谁能告诉我如何传递参数和创建对象实例?
【问题讨论】:
-
尝试时会发生什么? “不工作”并不能告诉我们您的问题是什么。
-
@bmargulies:添加了看到的错误信息。实际上,甚至不确定所采用的方法是否正确。所以希望有人指导我如何让整个工作正常。