Groovy 方法缺失
我在对象 Foo 内有一个闭包,在闭包内我定义了一个名为“myStaticMethod”的方法,一旦在对象外部调用闭包,我想解析该方法 Foo。。我还碰巧在我的对象 Foo 中“故意”有一个同名的静态方法。当我调用闭包时,我将“解析策略”设置为 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
}
}
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了解决这个问题,我最终在调用 FooTests 中的闭包之前重写了 invokeMethod。
在尝试解决这个问题时,我发现了一种非常奇怪的方法来拦截丢失的静态方法。将来可能对你们中的一些人有用。
-肯
To solve the problem, I ended up overriding the invokeMethod right before calling the closure in FooTests
While trying to solve this problem, i discovered a very weird way to intercept missing static methods. Might be useful to some of you in the future.
-Ken
不幸的是,静态方法不会被闭包属性解析拦截。我知道拦截这些的唯一方法是重写拥有闭包的类上的静态元类invokeMethod,例如:
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: