2012-11-04 135 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()方法)調用該方法。

閉包有額外的功能,當然,但我認爲這是考慮基本知識的好方法。