groovy - 在 Groovy DSL 中使用 'owner' 属性

标签 groovy dsl

让我们考虑一个简单的 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()
}

引用号:Is it possible to change the owner of a closure?

关于groovy - 在 Groovy DSL 中使用 'owner' 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13152278/

相关文章:

java - GRAILS:永久链接/slug 生成方法?

shell - Jenkins Pipeline 插件看似跳过命令

grails - Grails中的一对一关系显示

xml - 用另一个 Node 实例替换 XML Node

scala - 使用elastic4s客户端为Elasticsearch构建动态聚合查询

unit-testing - grails/groovy:单元测试时如何访问保存的域对象?

c# - 帮助学习使用 Irony for .net

java - 在 Xtext 编辑器中实现不区分大小写

scala - 在 Scala 中重命名 classOf

java - 从 Camel 中的 Exchange header 设置目录