Groovy Goodness: Redirecting Print Methods in Scripts
在我们的Java或Groovy应用程序中运行外部Groovy脚本很容易。例如,我们可以在应用程序中使用
在下面的示例中,我们使用变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | // 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! The answer is 2A' |
另一个选择是通过目录设置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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! The answer is 2A' |
用Groovy 2.4.10编写。