Last updated by
5 years ago
Page: Developer - Dynamic Method Injection, Version:0
Dynamic Method Injection
The core classes that make up the Grails dynamic method injection architecture are found in the org.codhaus.groovy.grails.commons.metaclass package. The org.codhaus.groovy.grails.commons.metaclass.ProxyMetaClass class extends the Groovy MetaClass to allow constructor, method and property interceptors to be set on the MetaClass which "intercept" calls.A Groovy MetaClass is what Groovy uses to dispatch method, constructor and property calls to objects with. These could be real methods or dynamically injected methods. Grails' ProxyMetaClass allows you to intercept calls to methods that may be real or not and choose whether to invoke the target "real" method at runtime. ProxyMetaClass tends to be used with instances and the setMetaClass method of GroovyObject as opposed to being registered within the MetaClassRegistry:GroovyObject go = ..// some object ProxyMetaClass pmc = ProxyMetaClass.getInstance(go.getClass()); go.setMetaClass(pmc)
- Interceptor - For intercepting method calls
- PropertyAccessInterceptor - For intercepting property getters/setters
- ConstructorInterceptor - For intercepting constructors
DynamicMethods dm = new AbstractDynamicMethodsInterceptor(){};
pmc.setInterceptor(dm);dm.addDynamicMethodInvocation( new AbstractDynamicMethodInvocation("hello") { public Object invoke(Object target, Object[] arguments) { System.out.println("world!"); } });
go.hello() // prints "world!"GroovyObject go = //.. created from somewhere
GroovyDynamicMethodsInterceptor i = new GroovyDynamicMethodsInterceptor(go);
i.addDynamicMethodInvocation( new AbstractDynamicMethodInvocation("hello") {
public Object invoke(Object target, Object[] arguments) {
System.out.println("world!");
}
});