2012-11-04 136 views
1

我读这样的:A closure looks a lot like a regular Java or Groovy code block, but actually it's not the same. The code within a regular code block (whether its a method block, static block, synchronized block, or just a block of code) is executed by the virtual machine as soon as it's encountered. With closures the statements within the curly brackets are not executed until the call() is made on the closure. In the previous example the closure is declared in line, but it's not executed at that time. It will only execute if the call() is explicitly made on the closure有关Groovy关闭的声明说明。

而且我想,这是怎么真实,在Java中,如果你有一个实例方法,当调用该方法,然后他们是如何说上面只执行的代码虚拟机一看到它就执行它? 如果我有一个方法func(){int a =5; return a+5;},只有当我的理解被调用时才会执行此操作。

回答

3

只需使用同步块或常规范围大括号即可更好地进行描述。它试图显示的是,当执行线程遇到一个普通的代码块时,它将继续执行内容。使用闭包定义时,块中的代码不会立即执行 - 它用于定义/实例化一个包含该逻辑的闭包对象(比如说clos),并可以通过clos.call()(或者只是clos( ))。

例如:

def x = 1 

synchronized(this) { 
    x = 1000 
} 
println x //x == 1000 

def x = 1 

Closure clos = { 
    x = 1000 
} 
println x // x == 1 
clos() // or clos.call() 
println x // x == 1000 

W/R/T方法/静态块:这我不清楚是否有某种微妙的方式,其中 “遭遇” 和“执行“可以在JVM语境中使用,使语句的这一部分正确,但出于实际的目的,这最多是误导性的。方法调用时仍然仅执行的,而不是由于它们的声明被位于代码执行的表观路径,如下可以在groovyConsole中运行以显示:

def x = 1 

void methodA() { 
    x = 1000 
} 

def b = { 
    x = x + 1 

} 

println x // x is still 1 
0

另一个类比,这不一定在技​​术上是准确的,就是将闭包视为具有单一方法的匿名内部类(闭包体)。

执行closure.call()或closure()(调用short()方法)调用该方法。

闭包有额外的功能,当然,但我认为这是考虑基本知识的好方法。