我对groovy很新。我试图将一些dSL格式的业务规则从java类传递给groovy。 Java类正在从外部源读取它。 Groovy类具有使用构建器读取此DSL的实现。如何将这些规则传递给groovy方法?
这是我的常规课程:
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[] {????} );
答案 0 :(得分:0)
Groovy闭包实际上是groovy.lang.Closure
类型的对象。目前尚不清楚您使用closure
方法的make
参数做了什么,因为您在方法中没有以任何方式使用它。
例如,您可以创建一个闭包,通过创建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;
}
}