2009-10-29 22 views
0

一類從Snipplr如何將一個新的閉包添加到常規

確定這裏是腳本代碼,在註釋中的問題,並拋出

class Class1 { 
    def closure = { 
     println this.class.name 
     println delegate.class.name 
     def nestedClos = { 
      println owner.class.name 
     } 
     nestedClos() 
    } 
} 

def clos = new Class1().closure 
clos.delegate = this 
clos() 

//Now I want to add a new closure to Class1 

def newClosure = { 
    println "new Closure" 
    println this.class.name 
    println delegate.class.name 
    def nestedClos = { 
     println owner.class.name 
    } 
    nestedClos() 
} 

//getAbc to create a property, not a method 
Class1.metaClass.getAbc = newClosure 

//What happens here is that the property abc is not used as a closure per se, it's used 
//as a property and when I execute it just run the closure and when I want to change 
//the delegate, a null pointer is thrown 
clos = new Class1().abc //abc executed instead of passing the reference closure 
clos.delegate = this //Exception!!!! 
clos() 

回答

0

好之外,它的完成它不是一種奇特的方式,但我有解決方案....是啊!

創建屬性作爲對象,以後分配封閉

class Class1 { 
    def closure = { 
     println this.class.name 
     println delegate.class.name 
     def nestedClos = { 
      println owner.class.name 
     } 
     nestedClos() 
    } 
} 

def clos = new Class1().closure 
clos.delegate = this 
clos() 

//Now I want to add a new closure to Class1 

def newClosure = { 
    println "new Closure" 
    println this.class.name 
    println delegate.class.name 
    def nestedClos = { 
     println owner.class.name 
    } 
    nestedClos() 
} 

//before edit 
//Class1.metaClass.abc = new Object() 
Class1.metaClass.abc = newClosure  


def cl = new Class1() 
//Before edit 
//For the sake of simplicity we are going to use & for the method 
//clos = cl.abc 
closs = cl.&abc 
clos.delegate = this 
clos() 
+0

好,它的工作原理,但我需要「落實」 ABC一樣關閉所有的情況...... – jjchiw 2009-10-29 13:37:54

相關問題