I understand that there are two obvious places in the Grails application where you can perform metaprogramming:
- Closing
init Bootstrap.groovy - Closing the
doWithDynamicMethods Plugin
The meta-programming that I refer to should be visible throughout the application, typical examples include adding (or replacing) methods of third-party classes.
String.metaClass.myCustomMethod = { /* implementation omitted */ }
The disadvantage (1) is that metaprogramming will not be applied when the application is dynamically reloaded. The disadvantage (2) is that I need to create and maintain the entire plugin just for the sake of a little metaprogramming.
Is there a better place for such metaprogramming?
Update
Following Ted's suggestion below, I added the following class to src/groovy
package groovy.runtime.metaclass.java.lang class StringMetaClass extends DelegatingMetaClass { StringMetaClass(MetaClass meta) { super(meta) } Object invokeMethod(Object object, String method, Object[] arguments) { if (method == 'hasGroovy') { object ==~ /.*[Gg]roovy.*/ } else { super.invokeMethod object, method, arguments } } }
Then it restarted the application and ran the following code in the Grails console:
assert 'mrhaki loves Groovy'.hasGroovy()
I got the following exception
groovy.lang.MissingMethodException: No signature of method: java.lang.String.hasGroovy() is applicable for argument types: () values: []
Am I doing something wrong or is there a reason why this does not work in a Grails application?
metaprogramming grails groovy
DΓ³nal
source share