Groovy 拦截对属性的调用
我正在尝试拦截对Groovy类上属性的所有调用。由于这没有按预期工作,我创建了以下示例:Groovy 拦截对属性的调用,groovy,Groovy,我正在尝试拦截对Groovy类上属性的所有调用。由于这没有按预期工作,我创建了以下示例: class TestClass { def getProperty(String key) { println "getting property: " + key } def invokeMethod(String method, args) { println "invoking method: " + method } def
class TestClass {
def getProperty(String key) {
println "getting property: " + key
}
def invokeMethod(String method, args) {
println "invoking method: " + method
}
def getFoo() {
return 1
}
}
tc.foo // 1
tc.getFoo() // 2
1) 做正确的事情,那就是调用getProperty。但是,2)有效(即返回1),但既不调用getProperty也不调用invokeMethod
还有什么方法可以拦截getfoo()调用吗
斯特凡几个月前我写了一篇文章。你可以看 请尝试以下代码:
TestClass.metaClass.invokeMethod = {
def metaMethod = delegate.metaClass.getMetaMethod(method,args)
println "executing $method with args $args on $delegate"
return metaMethod.invoke(delegate,args)
}
我不得不修改前面答案中的代码,以获得我认为您想要的:
TestClass.metaClass.invokeMethod = {method, args ->
def metaMethod = TestClass.metaClass.getMetaMethod(method,args)
println "executing $method with args $args on $delegate"
metaMethod.invoke(delegate,args) // could result in NPE
}
然后执行
tc.foo
tc.getFoo()
结果:
getting property: foo // println output
null // getProperty return is null
executing getFoo with args [] on TestClass@655538e5 // invokeMethod output
1 // metaMethod invocation
问题在于这里有两种不同的路径,即如何处理请求。对于询问属性,在我们进入meta类之前会调用getProperty方法-如果覆盖getProperty,则必须自己调用meta类。在invokeMethod的情况下,它通常在询问了meta类之后被询问。由于元类将响应您对getFoo()的请求,因此根本不会请求invokeMethod。如果让类实现GroovyInterceptable,那么首先会询问invokeMethod,方法与getProperty相同。这也解释了为什么使用meta类的方法会起作用