Categories
Development

Override existing properties with Groovy DSL delegate getter

In the example below I want to override all properties with my own delegate’s logic. But I can only do that for inexistent properties, the ones known at the compile time remains the same.

Is it possible to process them all?

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"
}

Output:

existingSymbol: Joe     <--- expecting "Ross" here
overriding property [inexistentSymbol] => Ross
inexistentSymbol: Ross

Leave an answer

Your email address will not be published. Required fields are marked *