我正在尝试使用Java和Groovy实现一些通用的DSL . 我的想法是使用类似 data { name 'my name' } 的语法并拦截所有方法调用 methodMissing ,我可以检查方法名称是否等于字段并通过运行闭包来设置它 . 我使用Java编写我的数据类,它看起来像这样 .

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;
    }
}

运行DSL脚本的代码就是这样

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' }");

问题是, closure.call() 返回 MissingMethodException

groovy.lang.MissingMethodException: No signature of method: Script1.name() is applicable for argument types: (java.lang.String) values: [my test data] 如何将方法调用重定向到其委托并查找其 methodMissing 方法?