在运行时获取groovy脚本自由变量

时间:2017-05-29 15:33:01

标签: java groovy

我想知道如何从Java代码中获取Groovy脚本中的所有自由变量。

Groovy脚本:

Integer v = a - b;
Integer k = 6 * v;

return k > 0;

从java调用:

Binding binding = new Binding();
GroovyShell groovyShell = new GroovyShell(binding);

Script script = groovyShell.parse(...);
script.getFreeVariables(); // == set with "a","b". Want something like this.

我知道粗鲁的方式 - script.run()然后抓住异常。在异常情况下,我得到var的名称,我没有传递给脚本。

2 个答案:

答案 0 :(得分:1)

常规:

def s0=a+b+2
s1=a+b+1
a=b*2
a+b+3 //the last expression will be returned. the same as return a+b+3

的java:

GroovyShell groovyShell = new GroovyShell();
Script script = groovyShell.parse(...);
Map bindings = script.getBinding().getVariables();

bindings.put("a",new Long(1));
bindings.put("b",new Long(2));

Object ret = script.run(); //a+b+3

//and if you changed variables in script you can get their values 
Object aAfter = bindings.get("a"); //4 because `a=b*2` in groovy
Object bAfter = bindings.get("b"); //2 not changed
//also bindings will have all undeclared variables
Object s1 = bindings.get("s1"); //a+b+1

//however declared variables will not be visible - they are local
Object s0 = bindings.get("s0"); //null

答案 1 :(得分:1)

默认情况下,groovy在运行时具有动态解析器​​,而不是在编译时。

您可以尝试捕获对这些属性的访问权限:

1 /

import org.codehaus.groovy.control.CompilerConfiguration;

abstract class MyScript extends groovy.lang.Script{
    public Object getProperty(String name){
        System.out.println("getProperty "+name);
        return new Long(5);
    }
}

CompilerConfiguration cc = new CompilerConfiguration()
cc.setScriptBaseClass( MyScript.class.getName() )

GroovyShell groovyShell = new GroovyShell(this.getClass().getClassLoader(),cc);

Script script = groovyShell.parse("1+2+a");

Object ret = script.run();

2 /

GroovyShell groovyShell = new GroovyShell();
Script script = groovyShell.parse("1+2+a");
Map bindings = new HashMap(){
    public Object get(Object key){
        System.out.println ("get "+key);
        return new Long(5);
    }
}

script.setBinding(new Binding(bindings));

Object ret = script.run();