Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: Delegating metaclass for an Interface?

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
{
    FooMetaClass(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?

like image 993
slim Avatar asked Oct 14 '22 17:10

slim


1 Answers

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)
}
like image 104
chanwit Avatar answered Dec 10 '22 16:12

chanwit