简体   繁体   中英

pass closure from java to groovy

I am pretty new to groovy. I am trying to pass some business rules which are in dSL format from java class to groovy. Java class is reading it from external sources. Groovy class has the implementation of reading this DSL using builder. How do I pass these rules to groovy method ?

this it my groovy class:

 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
}

and the test java class has this:

Class scriptClass = new GroovyClassLoader().parseClass( new File( "filename.groovy" ) ) ;
        GroovyObject groovyObj = (GroovyObject) scriptClass.newInstance();

        groovyObj.invokeMethod("make", new Object[] {????} );

A Groovy closure is actually an object of type groovy.lang.Closure . It's not clear what you're doing with the closure parameter of the make method as you're not using it in any way in the method.

For example you can create a closure that calls a method on the class by creating a MethodClosure subclass of Closure like so:

MethodClosure methodCall = new MethodClosure(someObject, "methodName");

A closure that does whatever you want can be created like this in Java:

Print out a message or anything else

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM