3

I need to pass a list of methods to execute inside the class with "closure way", see the code bellow

 class A{ def m1(){ println "Method1" } def m2(){ println "Method1" } def commands = { closure-> println "before" closure.call() println "after" } } A a = new A() a.commands{ println "before execute method m1" m1() //A need to execute m1 method of the class A println "after execute method m1" } 

When I comment the m1() the output is

 before before execute method m1 after execute method m1 after 

otherwise throw the exception MissingMethodException: No signature of method for method m1()

So, it does not recognize the m1() method as method of class A

1 Answer 1

7

Depending on what you are really trying to accomplish, you may want something like this...

class A{ def m1(){ println "Method1" } def m2(){ println "Method1" } def commands(closure) { def c = closure.clone() c.delegate = this println "before" c() println "after" } } 

The delegate gets an opportunity to respond to method calls that are made inside of the closure. Setting the delegate to this will cause the calls to m1() to be dispatched to the instance of A. You may also be interested in setting the resolveStrategy property of the closure. Valid values for resolveStrategy are Closure.DELEGATE_FIRST, Closure.OWNER_FIRST, Closure.DELEGATE_ONLY, Closure.OWNER_ONLY. The owner is the thing that created the closure and cannot be changed. The delegate can be assigned any object. When the closure makes method calls the methods may be handled by the owner or the delegate and the resolveStrategy comes into play in deciding which to use. The names DELEGATE_ONLY, OWNER_ONLY, DELEGATE_FIRST and OWNER_FIRST I think are self explanatory. If you need any more info, let me know.

I hope that helps.

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome ! Great explanation, the solution was simple as expected, don't you love Groovy? I will never back to Java, I don't see any reason to use Java instead of Groovy, I can't understand why Groovy is not so used like python, ruby mainly the fact it is naturally integrated with Java and it compiles for JVM, well, I think when the Java developers knows the Groovy will happen the same that happened with me, never back to Java. Thanks a lot, you saved my day!
@PlexQ "It also doesn't work well with Java 8." - Everything described above works just fine with Java 8. The rest of your comment is subjective and not particularly helpful.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.