gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:31:09 39 4
gpt4 key购买 nike

我想知道如何从 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() 然后捕获异常。在异常(exception)情况下,我得到了 var 的名称,但没有传递给脚本。

最佳答案

绝妙:

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

关于java - 在运行时获取 groovy 脚本自由变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44246081/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com