对于我正在编写的DSL,我有时会返回一个忽略所有调用的虚拟对象。
这有效:
class Dummy {
def methodMissing(String name, args) { print "Ignoring: "+name+" "+args }
}
def foo(guardCondition) {
if (guardCondition)
return new Dummy()
// ...
}
foo(true).with { bar('baz') }
但如果我尝试使用匿名类,则结果是No signature of method: <filename>.bar() is applicable for argument types: (java.lang.String) values: [baz]
即这不起作用:
if (guardCondition)
return new Object() { def methodMissing(String name, args) { print "Ignoring: "+name+" "+args } }
“包”方法也不起作用:
if (guardCondition)
return [ methodMissing : { name, args -> print "Ignoring: "+name+" "+args } ]