如何使用Groovy拦截Java应用程序中所有方法的执行?

Geo*_*Geo 5 groovy aop language-features metaprogramming interceptor

是否可以拦截应用程序中调用的所有方法?我想和他们做点什么,然后让他们执行.我试图覆盖这种行为Object.metaClass.invokeMethod,但它似乎不起作用.

这可行吗?

Ric*_*ler 2

你看过Groovy AOP吗?文档很少,但它允许您以与 AspectJ 概念上类似的方式定义切入点和建议。查看单元测试以获取更多示例

下面的示例将匹配对所有编织类型的所有调用,并在继续之前应用建议:

// 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
Run Code Online (Sandbox Code Playgroud)