1

I'm reading this: 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

And I'm thinking, how is this true, in Java if you have an instance method, the code is only executed when the method is called then how are they saying above that is executed by the VM as soon as it sees it ? If I have a method func(){int a =5; return a+5;} this will be executed only when called is my understanding.

4

2 に答える 2

3

説明は、同期されたブロックまたは通常のスコープ中括弧を使用した方が適切な場合があります。表示しようとしているのは、実行スレッドが通常のコードブロックにヒットすると、コンテンツの実行を継続することです。クロージャー定義では、ブロック内のコードはすぐには実行されません-そのロジックを含み、後でclos.call()(または単にclos()を介して実行できるクロージャーオブジェクト(たとえば、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
于 2012-11-04T05:07:21.360 に答える
0

必ずしも技術的に正確であるとは限らない別のアナロジーは、クロージャを単一のメソッド(クロージャの本体)を持つ匿名の内部クラスと考えることです。

closure.call()またはclosure()(call()の省略形)のいずれかを実行すると、その単一のメソッドが呼び出されます。

もちろん、クロージャには追加の機能がありますが、これは基本を考える良い方法だと思います。

于 2012-11-04T14:14:51.387 に答える