如何使用 Groovy 拦截 Java 应用程序中所有方法的执行? [英] How can I intercept execution of all the methods in a Java application using Groovy?
问题描述
是否可以拦截应用程序中调用的所有方法?我想和他们一起做点什么,然后让他们去执行.我试图在 Object.metaClass.invokeMethod
中覆盖此行为,但它似乎不起作用.
Is it possible to intercept all the methods called in a application? I'd like to do something with them, and then let them execute. I tried to override this behaviour in Object.metaClass.invokeMethod
, but it doesn't seem to work.
这可行吗?
推荐答案
你看过Groovy AOP?文档允许您可以在概念上以与 AspectJ 类似的方式定义切入点和通知.看看 单元测试一些更多的例子
Have you looked at Groovy AOP? There's very little documentation, but it allows you to define pointcuts and advice in a conceptually similar way as for AspectJ. Have a look at the unit tests for some more examples
下面的示例将匹配所有编织类型的所有调用,并在继续之前应用建议:
The example below will match all calls to all woven types and apply the advice before proceeding:
// aspect MyAspect
class MyAspect {
static aspect = {
//match all calls to all calls to all types in all packages
def pc = pcall("*.*.*")
//apply around advice to the matched calls
around(pc) { ctx ->
println ctx.args[0]
println ctx.args.length
return proceed(ctx.args)
}
}
}
// class T
class T {
def test() {
println "hello"
}
}
// Script starts here
weave MyAspect.class
new T().test()
unweave MyAspect.class
这篇关于如何使用 Groovy 拦截 Java 应用程序中所有方法的执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!