Wednesday, May 27, 2015

Groovy: Overloading [] and dot .

class Konf {
    // Initializing overloader
    static {
        // . read
        Konf.metaClass.getProperty = { String prop ->
            println "getProp $prop"
            this."${prop}"        
        }
        // . assignment
        Konf.metaClass.setProperty = { String prop, val ->
            println "setProp $prop $val"            
            this.metaClass."${prop}" = val
        }
    }
    // [] read
    def getAt( String key ) {
        println 'getAt'
        this."${key}"    
    }

    // [] set
    def putAt( String key, val ) {
        println "putAt $key $val" 
        this.metaClass."${key}" = val
    }

    def clear() {

    }
}

No comments: