Groovy Goodness: Redirecting Print Methods in Scripts
Particularly useful when dealing with external Groovy scripts, the Script class has special implementations of various print methods.
Join the DZone community and get the full member experience.Join For Free
Running 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. The
Script class, which is a base class to run script code, has an implementation for the
println methods. 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
Script class. If the property
out is available, then all calls to the
println methods are delegated to the object assigned to the
out property. 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 an 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
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.
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.