2011-11-14 51 views
35

tôi thấy đoạn mã này:.delegate có nghĩa là gì trong groovy?

def say = {println m} 
say.delegate = [m:2] 
say() 

Đó apperantly in 2. Làm thế nào để cho nó hoạt động? Nơi có thể tìm thấy tài liệu về .delegate? Google đã dẫn tôi đến trang Chuyển đổi ủy quyền không đề cập đến bất kỳ sự kiện nào.

+0

Trang thứ hai của google có tài liệu về nó: http://groovy.codehaus.org/Closures#Closures-this%2Cowner%2Canddelegate. Hi vọng điêu nay co ich. – Esailija

+2

http://mrhaki.blogspot.com/2009/11/groovy-goodness-setting-closures.html –

Trả lời

54

Đại biểu đóng cửa là một đối tượng được sử dụng để giải quyết các tham chiếu không thể được giải quyết trong phần thân của bản thân đóng. Nếu ví dụ của bạn đã được viết như thay vì điều này:

def say = { 
    def m = 'hello' 
    println m 
} 
say.delegate = [m:2] 
say() 

It in 'hello', bởi vì m có thể được giải quyết trong vòng đóng cửa. Tuy nhiên, khi m không được định nghĩa trong việc đóng cửa,

def say = { 
    println m 
} 
say.delegate = [m:2] 
say() 

các delegate được sử dụng để giải quyết các tài liệu tham khảo, và trong trường hợp này là một delegateMap mà các bản đồ m để 2.

+0

một cách tiện dụng để cung cấp các tham số mặc định cho việc đóng: 'def say = {def m = m?: 'Hello' ; println m} ' – coderatchet

+2

@thenaglecode Tôi nghĩ rằng bạn có nghĩa là điều này ' def say = {def m = it?: 'hello'; println m} ' –

11

Ba bất động sản đóng cửa , là này, chủ sở hữu, và ủy, Trong đại biểu nói chung được thiết lập để chủ sở hữu

def testClosure(closure) { 
    closure() 
} 
testClosure() { 
    println "this is " + this + ", super:" + this.getClass().superclass.name 
    println "owner is " + owner + ", super:" + owner.getClass().superclass.name 
    println "delegate is " + delegate + ", super:" + delegate.getClass().superclass.name 

    testClosure() { 
    println "this is " + this + ", super:" + this.getClass().superclass.name 
    println "owner is " + owner + ", super:" + owner.getClass().superclass.name 
    println "delegate is " + delegate + ", super:" + delegate.getClass().superclass.name 
    } 
} 

in

this is [email protected], super:groovy.lang.Script 
owner is [email protected], super:groovy.lang.Script 
delegate is [email protected], super:groovy.lang.Script 
this is [email protected], super:groovy.lang.Script 
owner is [email protected], super:groovy.lang.Closure 
delegate is [email protected], super:groovy.lang.Closure 
+4

Theo mặc định có thể là chủ sở hữu, nhưng điều gì thúc đẩy Groovy DSL là thực tế bạn có thể gán lại đại biểu cho bất kỳ đối tượng nào –