Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何为交互式会话创建有状态Groovy绑定_Java_Groovy - Fatal编程技术网

Java 如何为交互式会话创建有状态Groovy绑定

Java 如何为交互式会话创建有状态Groovy绑定,java,groovy,Java,Groovy,我正在构建一个基于groovy的工具,作为一个外接程序,我想提供一个交互式命令行,这部分工作正常,但是绑定没有在GroovyShell.evaluate()调用之间保持状态,我已经阅读了groovy文档,其中有一个示例使用了一个名为InteractiveGroovyShell的类,这在版本2.0.x上不可用 有没有办法配置普通GroovyShell来实现此功能 下面是我现在如何创建groovy shell的简化版本: CompilerConfiguration config = new Comp

我正在构建一个基于groovy的工具,作为一个外接程序,我想提供一个交互式命令行,这部分工作正常,但是绑定没有在
GroovyShell.evaluate()
调用之间保持状态,我已经阅读了groovy文档,其中有一个示例使用了一个名为
InteractiveGroovyShell
的类,这在版本2.0.x上不可用

有没有办法配置普通GroovyShell来实现此功能

下面是我现在如何创建groovy shell的简化版本:

CompilerConfiguration config = new CompilerConfiguration();
Binding binding = new Binding();
shell = new GroovyShell(binding, config);
shell.evaluate("def a = 20");
shell.evaluate("println a"); //this throws an exception telling the variable does not exist

对于不同的shell,应该重复使用相同的
绑定。绑定本身将保持以下状态:

import org.codehaus.groovy.control.CompilerConfiguration

def binding = new Binding()
def shell = new GroovyShell(binding)

shell.evaluate("a = 5")
assert binding.variables == [a:5]

shell.evaluate("println a; b = 6")
assert binding.variables == [a:5, b:6]

def shell2 = new GroovyShell(binding)

// even in a new shell the binding keep the state
shell2.evaluate("c = 7")
assert binding.variables == [a:5, b:6, c:7]

在groovy 2.0.5中工作时,应该为不同的shell重用相同的
绑定。绑定本身将保持以下状态:

import org.codehaus.groovy.control.CompilerConfiguration

def binding = new Binding()
def shell = new GroovyShell(binding)

shell.evaluate("a = 5")
assert binding.variables == [a:5]

shell.evaluate("println a; b = 6")
assert binding.variables == [a:5, b:6]

def shell2 = new GroovyShell(binding)

// even in a new shell the binding keep the state
shell2.evaluate("c = 7")
assert binding.variables == [a:5, b:6, c:7]
shell.evaluate("def a = 20");
在groovy 2.0.5中工作

shell.evaluate("def a = 20");
您只需要
a=20
,而不是
def a=20
。每个
evaluate
调用都会解析和编译一个单独的脚本,并且声明(无论是使用
def
还是使用显式类型,例如
int a=20
)都会成为该特定脚本中的局部变量,并且不会在绑定中存储任何内容。如果没有
def
命令,您将对一个未声明的变量进行简单赋值,该变量将进入绑定,因此在以后的
evaluate
调用中可见


您只需要
a=20
,而不是
def a=20
。每个
evaluate
调用都会解析和编译一个单独的脚本,并且声明(无论是使用
def
还是使用显式类型,例如
int a=20
)都会成为该特定脚本中的局部变量,并且不会在绑定中存储任何内容。如果没有
def
命令,您将对一个未声明的变量进行普通赋值,该变量将进入绑定,以便以后
求值
调用可以看到。

是否尝试运行此代码?我总是用同一个shell实例运行evaluate,实际上这对我来说不起作用。你试过运行这段代码吗?我总是使用同一个shell实例运行evaluate,实际上这对我来说是不起作用的。