0

I have this class structure:

interface bug
{
    def method()    
}

public class A implements bug{
    def method()
    {
        println "Works"
    }
}

A varaiable = new A()

bug.metaClass.invokeMethod {
    name,args ->
        println "Came here"
}

varaiable.method()

when I do this, I get Works. Why not Came here?

Where I'm doing the mistake?

EDIT:

Even if I do:

A.metaClass.invokeMethod {
    name,args ->
        println "Came here"
}

I'm getting only Works.

Community
  • 1
  • 1
batman
  • 4,728
  • 8
  • 39
  • 45

1 Answers1

1

You're changing the metaClass of A with

A.metaClass.invokeMethod { name,args ->
    println "Came here"
}

After you construct the variable. If you put this block before the line

A varaiable = new A()

It should work as you'd expect.

To get round this, you can use:

ExpandoMetaClass.enableGlobally()

And instances will check back with the metaClass every invocation, however as expected this can slow things down

tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • Thanks, it works for this case. But what I'm trying is to add intercept calls to `WebElement` (Selenium). But doing the same doesnt work there. Where `WebElement` is an interface. – batman May 15 '14 at 10:25
  • It should work if you declare the `invokeMethod` metaclass method on `Bug` **before** you make an instance of `A`... What version of Groovy? – tim_yates May 15 '14 at 10:53
  • Groovy.2.2.0. This is what I'm doing I have a script where I have code like this: `WebElement.metaClass.invokeMethod . . . `. And in the class I call this `script.run()`. So eventually all calls to `WebElement` should be intercepted right? – batman May 15 '14 at 11:02
  • Does it work if you add `ExpandoMetaClass.enableGlobally()`? It might be that the web elements are getting constructed earlier than your metaClass addition... – tim_yates May 15 '14 at 11:04
  • Thats going as recursion. This is my code. `ExpandoMetaClass.enableGlobally() WebElement.metaClass.invokeMethod { String methodName, args -> invokeMethod(methodName, args) }`. But that goes infinite loop!I'm trying to log the calls and then call the original method again – batman May 15 '14 at 11:17
  • Try http://stackoverflow.com/questions/10125903/groovy-overriding-invokemethod-for-a-single-instance – tim_yates May 15 '14 at 11:37