How to intercept the execution of all methods in a Java application using Groovy?

Is it possible to intercept all the methods called in the application? I would like to do something with them and then let them do it. I tried to override this behavior in Object.metaClass.invokeMethod, but it does not work.

Is this doable?

+5
source share
2 answers

Have you watched Groovy AOP ? There is very little documentation , but it allows you to define pointcut and tips in a conceptually similar way as for AspectJ. Take a look at unit tests for some examples.

:

// 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
+2

, Object.metaClass.invokeMethod , , Groovy X, metaClass X, metaClass (es). , " intValue intercepted"

Integer.metaClass.invokeMethod = {def name, def args ->
  System.out.println("method $name intercepted")
}

6.intValue()

// Reset the metaClass  
Integer.metaClass = null  

:

Object.metaClass.invokeMethod = {def name, def args ->
  System.out.println("method $name intercepted")
}

6.intValue()

// Reset the metaClass  
Object.metaClass = null

: " , ?", , :

  • Groovy , Java
  • Groovy/Java Groovy/Java library

, Groovy, GroovyInterceptable, , invokeMethod() , . (.. , / ), , invokeMethod() @Mixin, .

, Java-, DelegatingMetaClass.

+1

All Articles