2

I'ld like to wrap all methods of a class a generic way. So I assume I don't know the methods the class is implementing and AOP is not an alternative.

Groovy metaprogramming allows to redefine methods even with parameters but how to do that when you get a list of parameters from reflection.

someClass.metaClass.methods.each { method ->
    someClass.metaClass.'${method.name}' =  { /* how to define parameters knowing I get them from method.parameterTypes */

    }
}

Thanks in advance for the help.

Fiftoine
  • 271
  • 5
  • 17

1 Answers1

4

What about invokeMethod ?

Update: As @Tim commented, you can use getMetaMethod to execute the old method:

class A {
  def methodA(String a) { "executing methodA..." }
  def methodB(String b, Float c) {}
  def methodC() {}
}

A.metaClass.invokeMethod = { String method, args ->
  def ret = delegate.class.metaClass.getMetaMethod(method, args)?.invoke( delegate, args )
  "[intercepted $method] $ret"
}

def a = new A()

assert a.methodA("a") == "[intercepted methodA] executing methodA..."
Will
  • 14,348
  • 1
  • 42
  • 44
  • And then how would you invoke the method before redefinition? – Fiftoine Apr 04 '13 at 11:57
  • I tried with redefining invokeStaticMethod but it doesn't work... or i'm doing it wrong – Fiftoine Apr 04 '13 at 12:53
  • Thx for the help, I got something that works for existing methods... How could I do that when the called method is handled by the invokeMissingMethod definition? – Fiftoine Apr 08 '13 at 13:38
  • @Fiftoine, i think that's a subject a for a new question :-). And that is very aspect-ish. You wanna intercept the interception. – Will Apr 08 '13 at 15:24
  • Yeah @WillP, actually I want to override all grails domain object methods to secure them... And as grails inject a lot of dynamic methods using methodMissing, i'd like to intercept that too... – Fiftoine Apr 09 '13 at 09:24