如何捕获GroovyShell输出?

时间:2013-07-22 11:02:03

标签: java groovy groovyshell

我使用GroovyShell类创建了一个groovy引擎。 然后我用“评估”方法运行一堆语句 有没有办法捕获引擎的输出,所以我可以得到“println”调用输出?
目前它是stdout,虽然它是一个摇摆应用程序。

2 个答案:

答案 0 :(得分:2)

您可以将自定义Writer(例如StringWriter)分配给绑定中的out属性,并将其传递给GroovyShell。

def binding = new Binding();
binding.setProperty("out", new YourWriter())
new GroovyShell(binding);

答案 1 :(得分:1)

您可以使用scriptBaseClass方法设置println,并且您可以在值的基础上自由操作。请注意,如果需要,用户仍然可以System.out.printlnyou can blacklist

import org.codehaus.groovy.control.CompilerConfiguration

def script = """
  a = 10
  println a
  println "echo"
"""

abstract class Printer extends Script {
  void println(obj) {
    this.binding.printed << obj
  }
}

def config = new CompilerConfiguration(scriptBaseClass: Printer.class.name)
def binding = new Binding([printed: []])

new GroovyShell(this.class.classLoader, binding, config).evaluate script

assert binding.variables.printed.contains( 10 )
assert binding.variables.printed.contains( "echo" )
相关问题