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?