views:

344

answers:

1

Using Groovy's package name convention, I can intercept Groovy method calls to a Java method like so:

package groovy.runtime.metaclass.org.myGang.myPackage

class FooMetaClass extends groovy.lang.DelegatingMetaClass
{
    StringMetaClass(MetaClass delegate)
    {
        super(delegate);
    }

    public Object getProperty(Object a, String key)
    {
        return a.someMethod(key)
    }
}

This works fine if I really create an object of class Foo:

def myFoo = new Foo()
def fooProperty = myFoo.bar // metaclass invokes myFoo.someMethod("bar")

However what if Foo is an interface, and I want to intercept method calls to any implementation of it?

def myFoo = FooFactory.create()   // I don't know what class this will be
fooProperty = myFoo.bar

Is there a way to achieve this without having a DelegatingMetaClass for every known implementation of the Interface?

+1  A: 

You can create a class named "groovy.runtime.metaclass.CustomMetaClassCreationHandle" to globally handle metaclass creation process.

Inside this class, you can override this method:

protected MetaClass createNormalMetaClass(Class theClass, MetaClassRegistry registry) {
  // if theClass instanceof Foo, return your special metaclass
  // else return super.createNormalMetaClass(theClass, registry)
}
chanwit
Perfect. Thanks.
slim