Greedydp
Greedydp

Reputation: 205

can not override invokeMethod inherited from GroovyObject

Since every Groovy object implements GroovyObject interface, i would try to override invokeMethod(), here is my test :

class MyGrrovyClass {

  static test(){
      println 'i am in test'
  }

  Object invokeMethod(String name, Object args){
    log.info('method intercepted')
    def metaClass = InvokerHelper.getMetaClass(this)
    def result = metaClass.invokeMethod(this, name, args)
    return result
  }

  public static void main(String[] args) {
    test()
  }
}

but it seems doesn't work, i've never seen log message in my console

My second question is : GroovyInterceptable is the subinterface of GroovyObject, what the difference between that i override directly invokeMethod of GroovyObject and i implement invokeMethod of GroovyInterceptable interface?

thanks

Upvotes: 2

Views: 686

Answers (1)

Mark
Mark

Reputation: 612

According to the documentation (http://groovy.codehaus.org/Using+invokeMethod+and+getProperty) you must implement GroovyInterceptable to intercept existing methods I think this answers your first and second questions!

I made some slight changes to get your sample class working although was surprised to see that my println was intercepted but not System.out.println - this meant that I was getting a stack overflow because I originally had a simple println in the invokeMethod and that was getting recursively called.

class MyGrrovyClass implements GroovyInterceptable {


    def test(){
        println 'i am in test'
    }


    def invokeMethod(String name, args){

        System.out.println('method intercepted: '+ name)

        def result= metaClass.getMetaMethod(name, args).invoke(this, args)
    }
}

def mgc= new MyGrrovyClass()
mgc.test()

Upvotes: 4

Related Questions