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.

有帮助吗?

解决方案

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top