8

I'm trying to implement a somewhat general DSL with Java and Groovy. The idea is to have a syntax like data { name 'my name' } and to intercept all the method calls with methodMissing where I can check that the method name equals to a field and set it up by running the closure. I use Java to write my data class and it looks like this.

public class TestData {
    @Getter @Setter
    protected String name;

    public void call(Closure closure) {
        closure.setResolveStrategy(Closure.DELEGATE_FIRST);
        closure.setDelegate(this);
        closure.call();
    }

    public Object methodMissing(String name, Object args) {
        // here we extract the closure from arguments, etc
       return "methodMissing called with name '" + name + "' and args = " + argsList;
    }
}

The code to run a DSL script is this

    TestData testData = new TestData();
    Binding binding = new Binding();
    GroovyShell shell = new GroovyShell(binding);
    binding.setVariable("data", testData);
    Object result = shell.evaluate("data { name 'my test data' }");

The problem is, closure.call() returns a MissingMethodException:

groovy.lang.MissingMethodException: No signature of method: Script1.name() is applicable for argument types: (java.lang.String) values: [my test data] How can I make it redirect the method calls to its delegate and to look for its methodMissing method?

Andrew Sokolov
  • 277
  • 2
  • 12
  • 1
    Instead of using evaluate, you can use the parse method which returns a Script Object and then call setDelegate on that before invoking its run method. – adamcooney May 10 '18 at 16:22
  • Thank you. This helps, but now `methodMissing` is always called for the `TestData` instance I set as the script's delegate. `closure.setDelegate(value); closure.run()` doesn't call the `value`'s `methodMissing()` – Andrew Sokolov May 10 '18 at 17:10
  • 4
    I've found the solution: `TestData` should extend `GroovyObjectSupport` which contains a `MetaClass` which, in turn, redirects all missing method calls to the `methodMissing` of the right object. – Andrew Sokolov May 11 '18 at 13:34
  • @AndrewSokolov Why not write your own solution and accept it as answer. – aristotll Jan 10 '23 at 02:16

0 Answers0