[英]pass closure from java to groovy
我對groovy很陌生。 我正在嘗試將dSL格式的一些業務規則從java類傳遞到groovy。 Java類正在從外部來源讀取它。 Groovy類具有使用生成器讀取此DSL的實現。 如何將這些規則傳遞給常規方法?
這是我的時髦課:
def ruleSet=[:];
def displaySet=[:];
def when(String c1) {
['and': { String c2 ->
['then': { String result ->
['display':{String status ->
constructRule(c1,c2,result,status)
}]
}]
}]
}
def make(closure){
when 'a=b' and 'c=d' then 'aaaa' display 'bbbb'
when "a1=b1" and "c1=d1" then "c1c1c1" display "d1d1d1"
println ruleSet
println displaySet
}
並且測試java類具有以下內容:
Class scriptClass = new GroovyClassLoader().parseClass( new File( "filename.groovy" ) ) ;
GroovyObject groovyObj = (GroovyObject) scriptClass.newInstance();
groovyObj.invokeMethod("make", new Object[] {????} );
Groovy閉包實際上是groovy.lang.Closure
類型的對象。 目前尚不清楚您正在使用make
方法的closure
參數做什么,因為您沒有在該方法中以任何方式使用它。
例如,您可以通過創建Closure的MethodClosure子類來創建一個在類上調用方法的閉包,如下所示:
MethodClosure methodCall = new MethodClosure(someObject, "methodName");
可以像這樣在Java中創建一個可以做任何事情的閉包:
打印消息或其他任何內容
public class FooClosure extends Closure {
public FooClosure(Object owner, Object thisObject) {
super(owner, thisObject);
parameterTypes = new Class[1];
parameterTypes[0] = String.class;
maximumNumberOfParameters = 1;
}
public java.lang.Object doCall(String message) {
System.out.println(message);
return Closure.DONE;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.