You can just assign your custom Writer (eg. StringWriter) to out
property in the binding and pass it to the GroovyShell.
def binding = new Binding();
binding.setProperty("out", new YourWriter())
new GroovyShell(binding);
Вопрос
I create a groovy engine with the GroovyShell class.
Then I run a bunch of statements with the "evaluate" method.
Is there a way to catch the output of the engine so I can get "println" calls output?
Currently it goes to stdout although it is a swing application.
Решение
You can just assign your custom Writer (eg. StringWriter) to out
property in the binding and pass it to the GroovyShell.
def binding = new Binding();
binding.setProperty("out", new YourWriter())
new GroovyShell(binding);
Другие советы
You can set a scriptBaseClass
with a println
method and you are free to operate on top of the value. Remember the user still can do System.out.println
, but you can blacklist it, if needed.
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" )