让我们考虑一个简单的 Groovy DSL
execute {
sendNotification owner
sendNotification payee
}
执行的实现是
public static void execute(Closure dslCode) {
Closure clonedCode = dslCode.clone()
def dslDelegate = new MyDslDelegate(owner: 'IncCorp', payee: 'TheBoss')
clonedCode.delegate = dslDelegate
clonedCode.call()
}
和自定义代表是
public static class MyDslDelegate {
def owner
def payee
void sendNotification(to) {
println "Notification sent to $to"
}
}
execute运行块的预期结果是
Notification sent to IncCorp
Notification sent to TheBoss
实际的是
Notification sent to class package.OwnerClassName
Notification sent to TheBoss
问题是ownerGroovy 本身的保留属性,由于 Groovy实现Closure,没有resolveStrategy选项有助于owner用委托的自定义值替换值getPropertyClosure
public Object getProperty(final String property) {
if ("delegate".equals(property)) {
return getDelegate();
} else if ("owner".equals(property)) {
return getOwner();
...
} else {
switch(resolveStrategy) {
case DELEGATE_FIRST:
...
}
我的问题是,有人如何能够产生这种限制并owner在自定义 DSL 中使用属性名称?