简体   繁体   English

创建全局Groovy闭包

[英]Creating Global Groovy Closure

I'm trying to learn how to create a global closure in groovy (like the println closure). 我正在尝试学习如何在groovy中创建全局闭包(如println闭包)。 I have the following code: 我有以下代码:

a.groovy 杂种

def header = Tools.&header
header 'groovy script a'

b.groovy 常规

def header = Tools.&header
header 'groovy script b'

tools.groovy tools.groovy

class Tools {
    def static header(String str) {
        println("\n${str}")
        println("-" * 80)
    }
}

I would like to avoid: 我想避免:

def header = Tools.&header

in every groovy script where I would like to use the Tools.header() (and just use header closure when I import the tools package). 在每个我想使用Tools.header()的常规脚本中(并且在导入工具包时仅使用标头闭包)。 I tried to put the definition after the Tools class, but that did not work. 我试图将定义放到Tools类之后,但这没有用。 Can this be done? 能做到吗? Is there a better way to handle this? 有没有更好的方法来解决这个问题?


EDIT: (using a metaClass and the evaluate method unless there is a simpler way to include an external script): 编辑:(除非有更简单的方法来包括外部脚本,否则请使用metaClass和评估方法):

a.groovy 杂种

evaluate(new File("Tools.groovy"))
header 'groovy script a'

b.groovy 常规

evaluate(new File("Tools.groovy"))
header 'groovy script b'

tools.groovy tools.groovy

Object.metaClass.header = {str ->
    println("\n${str}")
    println("-" * 80)
}

println is not actually a global closure. println实际上不是全局闭包。 It's a method that is added to java.lang.Object using groovy metaprogramming. 这是使用groovy元编程添加到java.lang.Object方法。 Because all classes extend Object - including the script class that wraps code run in the groovy console - println can be called from anywhere. 因为所有类都扩展了Object包括包装在groovy控制台中运行的代码的脚本类-所以println可以在任何地方调用。

You can add your own methods to Object . 您可以将自己的方法添加到Object Run this code in the Groovy console to see it in action: 在Groovy控制台中运行以下代码以查看其运行情况:

// Add a global sayHello() method
Object.metaClass.sayHello = {-> println 'hello' }

// Try it out
sayHello()

import static Tools.header should do the trick. import static Tools.header应该可以解决问题。 You don't need a closure in this case as you call simple method. 在这种情况下,您在调用简单方法时不需要关闭。 If you'll have to pass header as a closure somewhere in your code of a.groovy or b.groovy the &header still could be used. 如果必须在header a.groovyb.groovy的某个地方传递header作为闭包, a.groovy仍可以使用&header

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM