Search code examples
groovymop

Groovy methodMissing


I have a closure within an object Foo and inside the closure i define a method called 'myStaticMethod' that I want to resolve once the closure is called outside the object Foo. I also happen to have 'on purpose' a static method within my object Foo with the same name. When I call the closure i set the 'resolve strategy' to DELEGATE_ONLY to intercept the call to myStaticMethod that is defined within the closure.

I tried to achieve that through missingMethod but the method is never intercepted. When i make the Foo.myStaticMethod non static, the method is intercepted. I don't quite understand why this is happening though my resolve strategy is set to DELEGATE_ONLY. having the Foo.myStaticMethod static or not shouldn't matter or I am missing something

class Foo {
   static myclosure = {
       myStaticMethod()
   }

   static def myStaticMethod() {}
}


class FooTest {
  def c = Foo.myclosure
  c.resolveStrategy = Closure.DELEGATE_ONLY
  c.call()

  def missingMethod(String name, def args) {
    println $name
  }
}

Solution

  • Static methods unfortunately aren't intercepted by the closure property resolution. The only way that I know to intercept those is to override the static metaClass invokeMethod on the class that owns the closure, ex:

    class Foo {
       static myclosure = {
           myStaticMethod()
       }
    
        static myStaticMethod() {
           return false
       }
    }
    
    Foo.metaClass.'static'.invokeMethod = { String name, args ->
        println "in static invokeMethod for $name"
        return true
    }
    
    def closure = Foo.myclosure
    assert true == closure()