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?
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With