简体   繁体   English

在运行时获取groovy脚本免费变量

[英]Get groovy script free variables in runtime

I want to know how get all free variables from Groovy script from Java code. 我想知道如何从Java代码从Groovy脚本中获取所有可用变量。

Groovy script: Groovy脚本:

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

return k > 0;

Call from java: 从Java呼叫:

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

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

I know rude way - script.run() and then catch exception. 我知道粗鲁的方式script.run()然后捕获异常。 In exception I get name of var that I don't pass to the script. 在例外情况下,我得到的var名称没有传递给脚本。

groovy: 常规:

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: 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

by default groovy has dynamic resolver at runtime and not at compiletime. 默认情况下,groovy在运行时而非编译时具有动态解析器​​。

you can try catch access to those properties: 您可以尝试捕获对这些属性的访问:

1/ 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/ 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();

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

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