![](/img/trans.png)
[英]Building a runner/executor/interpreter for a simple Java/Groovy DSL
[英]Groovy DSL with Java
自從我開始使用Groovy以來已經過了幾天。 但是,通過所有的閱讀和沖浪,我還無法弄清楚如何實現自己的想法。 所以,請原諒我。 一如既往地感謝您的幫助。
我要實現的目標是 :我有一個Java類,例如ServiceClass
,它具有一些方法( getMethod()
, postMethod()
等)來發出一些REST GET / POST請求( postMethod()
運行就可以了)。 現在,我想公開一個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
,但需要更多代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.