使用Groovy DSL委托getter覆盖现有属性

时间:2020-02-15 22:01:34

标签: groovy dsl

在下面的示例中,我想用我自己的委托人的逻辑覆盖 all 属性。但是我只能对不存在的属性执行此操作,编译时已知的属性保持不变。

是否可以全部处理?

val errorLog: ... by composeProperties(listSO(...)) { addToSet(it) }

输出:

def dsl(Closure action) {
    action.delegate = new Object() {
        Object getProperty(String name) {
            println "overriding property [$name] => Ross"
            return "Ross"
        }
    }
    action()
}

dsl {
    def existingSymbol = "Joe"
    println "existingSymbol: $existingSymbol"
    println "inexistentSymbol: $inexistentSymbol"
}

1 个答案:

答案 0 :(得分:0)

def existingSymbol = "Joe"

中的问题

使用def声明一个具有最高优先级的新局部变量。

检查以下代码:

def dsl(Closure action) {
    def delegate = new Object() {
        Object getProperty(String name) {
            return "Ross"
        }
    }
    action=action.rehydrate(delegate,delegate,delegate)
    action.call()
}

dsl {
    def existingSymbol = "Joe"
    println "1 existingSymbol: ${existingSymbol}"
    println "2 existingSymbol: ${this.existingSymbol}"
}
dsl {
    existingSymbol = "Joe"
    println "3 existingSymbol: ${existingSymbol}"
    println "4 existingSymbol: ${this.existingSymbol}"
}

输出:

1 existingSymbol: Joe
2 existingSymbol: Ross
3 existingSymbol: Ross
4 existingSymbol: Ross