2012-09-05 59 views
1

我在玩Groovy,我想知道爲什麼這段代碼沒有工作?Groovy運行時方法攔截

package test 

interface A { 
    void myMethod() 
} 

class B implements A { 
    void myMethod() { 
     println "No catch" 
    } 
} 

B.metaClass.myMethod = { 
    println "Catch!" 
} 

(new B()).myMethod() 

它打印出No catch,而我希望它打印Catch!代替。

+0

相關[Groovy的元編程](http://stackoverflow.com/q/11892620/462015) –

回答

8

這是Groovy中的一個錯誤,JIRA中存在一個公開的問題:無法通過元類覆蓋方法,它們是接口實現的一部分GROOVY-3493。不是重寫B.metaClass.myMethod的

1

,嘗試以下操作:

B.metaClass.invokeMethod = {String methodName, args -> 
    println "Catch!" 
} 

blog post把它描述得非常好。

0

有一種解決方法,但它只適用於所有類而不適用於特定實例。

元類改性前結構:

interface I { 
    def doIt() 
} 

class T implements I { 
    def doIt() { true } 
} 

I.metaClass.doIt = { -> false } 
T t = new T() 
assert !t.doIt() 

元類修改施工後:

interface I { 
    def doIt() 
} 

class T implements I { 
    def doIt() { true } 
} 

T t = new T() 
// Removing either of the following two lines breaks this 
I.metaClass.doIt = { -> false } 
t.metaClass.doIt = { -> false } 
assert !t.doIt()