Embedding Groovy in Java (Binding)

Deadly 提交于 2019-12-01 11:58:32

The binding only applies to scripts, not to classes. If your Groovy code were a script, i.e. just the content of the main method without the surrounding class body

println 'From Java: '+SRESULT
SRESULT = 'bar'

then it would produce the result you expect. In particular you must not declare the SRESULT variable in the script, i.e.

def SRESULT = 'bar'

would not work. This is because the declarations (with def or with an explicit type) create local variables within the script, they do not assign to the binding.

Given Test.java containing:

import groovy.lang.Binding ;
import groovy.lang.GroovyShell ;
import java.io.File ;

public class Test {
    public static void main( String[] args ) throws Exception {
        Binding binding = new Binding() ;
        binding.setVariable( "SRESULT", "foo" ) ;

        GroovyShell gs = new GroovyShell( binding ) ;
        gs.evaluate( new File( "script.groovy" ) ) ;

        String sResult = (String)binding.getVariable( "SRESULT" ) ;
        System.out.printf( "FROM GROOVY: %s\n", sResult ) ;
    }
}

And script.groovy containing:

println "From Java: $SRESULT"
SRESULT = 'bar'

We can compile Test.java by doing:

javac -cp $GROOVY_HOME/embeddable/groovy-all-2.1.1.jar:. Test.java

And then running it with:

java -cp $GROOVY_HOME/embeddable/groovy-all-2.1.1.jar:. Test

Gives the output:

From Java: foo
FROM GROOVY: bar
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!