Groovy: metaclass delegation for an interface?

Using the Groovy package naming convention, I can intercept the calls to the Groovy method for the Java method as follows:

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 for any implementation?

 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 MetaClass delegation for every known interface implementation?

+4
source share
1 answer

You can create a class called "groovy.runtime.metaclass.CustomMetaClassCreationHandle" to globally handle the process of creating a metaclass.

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) } 
+3
source

All Articles