简体   繁体   English

Groovy:向闭包添加方法

[英]Groovy: add a method to a closure

I have the following closure 我有以下关闭

def closure = {
   println ("closure code")
}

And i would like to add a method to it. 我想为其添加一种方法。 but if I try 但是如果我尝试

 closure.metaClass.fun = { c->
        c.call();
        println ("extra code");
 }   

I get an Exception 我得到一个例外

groovy.lang.MissingPropertyException: No such property: fun for class: org.codehaus.groovy.runtime.metaclass.ClosureMetaClass

Reading another answer, i also blindly tried to call 阅读另一个答案,我也盲目地打电话给

ExpandoMetaClass.enableGlobally()

but it's not working. 但它不起作用。

Is there a way to achive what I want? 有没有办法实现我想要的?

You can do: 你可以做:

def closure = {
    println "closure code"
}

closure.getMetaClass().fun = { ->
    delegate.call()
    println "extra code"
}   

closure.fun()

Which prints: 哪些打印:

closure code
extra code

Another simpler approach could be: 另一种更简单的方法可能是:

def closure = {    
    println "closure code" 
}  

closure.fun = { ->  
    closure()
    println "extra code" 
}     

closure.fun()

The downside of this approach is that I'm referencing the closure variable directly though, instead of going through the delegate. 这种方法的缺点是我直接引用了闭包变量,而不是通过委托。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM