让我们考虑一个简单的 Groovy DSL
execute {
sendNotification owner
sendNotification payee
}
execute的实现是
public static void execute(Closure dslCode) {
Closure clonedCode = dslCode.clone()
def dslDelegate = new MyDslDelegate(owner: 'IncCorp', payee: 'TheBoss')
clonedCode.delegate = dslDelegate
clonedCode.call()
}
自定义委托(delegate)是
public static class MyDslDelegate {
def owner
def payee
void sendNotification(to) {
println "Notification sent to $to"
}
}
运行的预期结果execute
block 是
Notification sent to IncCorp
Notification sent to TheBoss
实际情况是
Notification sent to class package.OwnerClassName
Notification sent to TheBoss
问题是owner
是 Groovy Closure
中的保留属性本身并没有resolveStrategy
选项有助于替换owner
由于 Groovy 具有来自委托(delegate)的自定义值的值 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 中的属性名称?
最佳答案
这有点像黑客,但这应该可以让你得到你想要的,而无需改变 Groovy 源代码:
public static void execute(Closure dslCode) {
Closure clonedCode = dslCode.clone()
def dslDelegate = new MyDslDelegate(owner: 'IncCorp', payee: 'TheBoss')
clonedCode.@owner = dslDelegate.owner
clonedCode.resolveStrategy = Closure.DELEGATE_ONLY
clonedCode.delegate = dslDelegate
clonedCode.call()
}
关于groovy - 在 Groovy DSL 中使用 'owner' 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13152278/