让我们考虑一个简单的 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
问题是owner
Groovy 本身的保留属性,由于 Groovy实现Closure
,没有resolveStrategy
选项有助于owner
用委托的自定义值替换值getProperty
Closure
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 中使用属性名称?