本文介绍了我如何使用Groovy拦截Java应用程序中所有方法的执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



这是可以做到的吗? 您有没有看过?很少有,但它允许您可以使用概念上类似于AspectJ的方式来定义切入点和建议。看看以获取更多示例

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

  // aspect MyAspect 
class MyAspect {
static aspect = {
//将所有呼叫都匹配到所有包中的所有类型
def pc = pcall(*。*。*)

//将匹配呼叫的建议应用于
(pc){ctx - >
println ctx.args [0]
println ctx.args.length
return proceed(ctx.args)
}
}
}
// class T
class T {
def test(){
printlnhello
}
}
//脚本从这里开始
weave MyAspect.class
new T()。test()
unweave MyAspect.class


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.

Is this doable?

解决方案

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应用程序中所有方法的执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 08:02