简体   繁体   English

将闭包从Java传递到groovy

[英]pass closure from java to groovy

I am pretty new to groovy. 我对groovy很陌生。 I am trying to pass some business rules which are in dSL format from java class to groovy. 我正在尝试将dSL格式的一些业务规则从java类传递到groovy。 Java class is reading it from external sources. Java类正在从外部来源读取它。 Groovy class has the implementation of reading this DSL using builder. Groovy类具有使用生成器读取此DSL的实现。 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: 并且测试java类具有以下内容:

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 . Groovy闭包实际上是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. 目前尚不清楚您正在使用make方法的closure参数做什么,因为您没有在该方法中以任何方式使用它。

For example you can create a closure that calls a method on the class by creating a MethodClosure subclass of Closure like so: 例如,您可以通过创建Closure的MethodClosure子类来创建一个在类上调用方法的闭包,如下所示:

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

A closure that does whatever you want can be created like this in Java: 可以像这样在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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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