本文整理自网络,侵删。
闭包是一个短的匿名代码块。它通常跨越几行代码。一个方法甚至可以将代码块作为参数。它们是匿名的。
下面是一个简单闭包的例子,它是什么样子。
class Example { static void main(String[] args) { def clos = {println "Hello World"}; clos.call(); } }
在上面的例子中,代码行 - {println“Hello World”}被称为闭包。此标识符引用的代码块可以使用call语句执行。
当我们运行上面的程序,我们将得到以下结果 -
Hello World
闭包中的形式参数
闭包也可以包含形式参数,以使它们更有用,就像Groovy中的方法一样。
class Example { static void main(String[] args) { def clos = {param->println "Hello ${param}"}; clos.call("World"); } }
在上面的代码示例中,注意使用$ {param},这导致closure接受一个参数。当通过clos.call语句调用闭包时,我们现在可以选择将一个参数传递给闭包。
当我们运行上面的程序,我们将得到以下结果 -
Hello World
下一个图重复了前面的例子并产生相同的结果,但显示可以使用被称为它的隐式单个参数。这里的'it'是Groovy中的关键字。
class Example { static void main(String[] args) { def clos = {println "Hello ${it}"}; clos.call("World"); } }
当我们运行上面的程序,我们将得到以下结果 -
Hello World
闭包和变量
更正式地,闭包可以在定义闭包时引用变量。以下是如何实现这一点的示例。
class Example { static void main(String[] args) { def str1 = "Hello"; def clos = {param -> println "${str1} ${param}"} clos.call("World"); // We are now changing the value of the String str1 which is referenced in the closure str1 = "Welcome"; clos.call("World"); } }
在上面的例子中,除了向闭包传递参数之外,我们还定义了一个名为str1的变量。闭包也接受变量和参数。
当我们运行上面的程序,我们将得到以下结果 -
Hello World Welcome World
在方法中使用闭包
闭包也可以用作方法的参数。在Groovy中,很多用于数据类型(例如列表和集合)的内置方法都有闭包作为参数类型。
相关阅读 >>
更多相关阅读请进入《Groovy》频道 >>
深入理解Java虚拟机 JVM高级特性与实践 周志明 第3版
这是一部从工作原理和工程实践两个维度深入剖析JVM的著作,是计算机领域公认的经典。