Groovy的优点:重定向脚本中的打印方法

Groovy Goodness: Redirecting Print Methods in Scripts

在我们的Java或Groovy应用程序中运行外部Groovy脚本很容易。例如,我们可以在应用程序中使用GroovyShell评估Groovy代码。如果我们的脚本包含println之类的打印方法,则可以重定向这些方法的输出。 Script类是运行脚本代码的基类,它具有printprintfprintln方法的实现。该方法的实现是在Script子类的一部分中或在添加到Script类的绑定中查找属性out。如果属性out可用,则对printprintfprintln方法的所有调用都委托给分配给out属性的对象。当使用printWriter实例时,我们有一个这样的对象,但是我们也可以为print方法的实现编写自己的类。如果未分配out属性,则后备将在System.out上打印。

在下面的示例中,我们使用变量ScriptText定义了一个外部脚本,但是它也可以是包含我们要运行的脚本内容的文件或其他源。我们分配自己的printWriter来封装StringWriter,以捕获对print方法的所有调用:

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'

另一个选择是通过目录设置Script对象的out属性:

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编写。