Wednesday, 18 September 2013

Can I add methods to a Groovy base Script dynamically, from Java?

Can I add methods to a Groovy base Script dynamically, from Java?

Although it's not standard practice, I'm curious if it's possible to
inject methods into a GroovyShell compilation context.
The idea is to have something like (in Java):
GroovyShell shell = new GroovyShell();
Script script = shell.parse("test()");
script.run();
Where I'd like to dynamically add methods that are invokable, where test()
has been listed.
I've experimented a bit with messing with the Script metaClass, but I
don't see a way to actually manipulate the metaClass from Java. In
particular, calling script.getMetaClass().getMethods().add(...) throws an
UnsupportedOperationException.
In essence, I'd like to define DSL call-points that invoke Java methods
rather than Groovy-based ones. I'm willing to write this part in Groovy
(and am aware of how to do this), but I'm genuinely curious if this is a
viable alternative approach, or if it's not, what the pitfalls are.
In short: how can I dynamically define a method that GroovyShell knows about?

No comments:

Post a Comment