Groovy Goodness: Redirecting Print Methods In Scripts
To run external Groovy scripts in our Java or Groovy application is easy to do.
For example we can use
GroovyShell to evaluate Groovy code in our applications.
If our script contains print methods like
println we can redirect the output of these methods.
Script class, which is a base class to run script code, has an implementation for the
The implementation of the method is to look for a property
out, either as part of a
Script subclass or in the binding added to a
If the property
out is available than all calls to
println methods are delegated to the object assigned to the
When we use a
PrintWriter instance we have such an object, but we could also write our own class with an implementation for the
out property the fallback is to print on
In the following example we have a external script defined with the variable
scriptText, but it could also be a file or other source with the contents of the script we want to run.
We assign our own
PrintWriter that encapsulates a
StringWriter to capture all invocations to the
// Groovy script to execute. def scriptText = ''' def s = "Groovy rocks!" // Print value of s. println s // Use printf for formatted printing. printf 'The answer is %X', 42 ''' // Assign new PrintWriter to "out" // variable of binding object. def stringWriter = new StringWriter() def shellBinding = new Binding(out: new PrintWriter(stringWriter)) // Create GroovyShell to evaluate script. def shell = new GroovyShell(shellBinding) // Run the script. shell.evaluate(scriptText) // Check the output of print, println and printf methods. assert stringWriter.toString() == 'Groovy rocks!\nThe answer is 2A' Another option is to directory set the `out` property of a `Script` object: def scriptText = ''' def s = "Groovy rocks!" // Print value of s. println s // Use printf for formatted printing. printf 'The answer is %X', 42 ''' def shell = new GroovyShell() // Parse script text and return Script object. def script = shell.parse(scriptText) // Assign new PrintWriter to "out" // variable of Script class. def stringWriter = new StringWriter() script.out = new PrintWriter(stringWriter) // Run the script. script.run() // Check the output of print, println and printf methods. assert stringWriter.toString() == 'Groovy rocks!\nThe answer is 2A'
Written with Groovy 2.4.10.