简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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