Groovy方法弥补

时间:2010-08-27 22:32:47

标签: groovy mop

我在一个对象 Foo 中有一个闭包,在闭包内我定义了一个名为' myStaticMethod '的方法,一旦在对象外调用闭包我想解决它。我也碰巧在我的对象Foo中使用相同名称的“有目的”静态方法。当我调用闭包时,我将'resolve strategy'设置为DELEGATE_ONLY来拦截对闭包中定义的 myStaticMethod 的调用。

我尝试通过 missingMethod 实现这一目标,但该方法从未被截获。当我使Foo。 myStaticMethod 非静态时,该方法被截获。虽然我的解决策略设置为DELEGATE_ONLY,但我不太明白为什么会发生这种情况。让 Foo.myStaticMethod 静止与否应该无关紧要或者我错过了什么

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
  }
}

2 个答案:

答案 0 :(得分:5)

为了解决这个问题,我在调用FooTests中的闭包之前最终覆盖了invokeMethod

Foo.metaClass.'static'.invokeMethod = { String name, args ->
     println "Static Builder processing $name "
}

在尝试解决这个问题时,我发现了一种非常奇怪的方法来拦截缺少的静态方法。将来可能对你们有些人有用。

 static $static_methodMissing(String name, args) {
    println "Missing static $name"
}

-Ken

答案 1 :(得分:3)

不幸的是,静态方法不会被闭包属性解析拦截。我知道拦截它们的唯一方法是覆盖拥有闭包的类的静态metaClass invokeMethod,例如:

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()
相关问题