开发者

How to add a new closure to a class in groovy

开发者 https://www.devze.com 2022-12-10 13:21 出处:网络
From Snipplr Ok here is the script code, in the comments is the question and the exception thrown class Class1 {

From Snipplr

Ok here is the script code, in the comments is the question and the exception thrown

class Class1 {
    def closure = {
        println this.class.name
        println delegate.class.name
        def nestedClos = {
            println owner.class.name
        }
        nestedClo开发者_Python百科s()
    }
}

def clos = new Class1().closure
clos.delegate = this
clos()

//Now I want to add a new closure to Class1

def newClosure = {
    println "new Closure"
    println this.class.name
    println delegate.class.name
    def nestedClos = {
        println owner.class.name
    }
    nestedClos()
}

//getAbc to create a property, not a method
Class1.metaClass.getAbc = newClosure

//What happens here is that the property abc is not used as a closure per se, it's used
//as a property and when I execute it just run the closure and when I want to change
//the delegate, a null pointer is thrown
clos = new Class1().abc //abc executed instead of passing the reference closure
clos.delegate = this  //Exception!!!!
clos()


Ok, It's done it's not a fancy way, but I have the solution....yeah!

Create the property as object and later assign the closure

class Class1 {
    def closure = {
        println this.class.name
        println delegate.class.name
        def nestedClos = {
            println owner.class.name
        }
        nestedClos()
    }
}

def clos = new Class1().closure
clos.delegate = this
clos()

//Now I want to add a new closure to Class1

def newClosure = {
    println "new Closure"
    println this.class.name
    println delegate.class.name
    def nestedClos = {
        println owner.class.name
    }
    nestedClos()
}

//before edit
//Class1.metaClass.abc = new Object()
Class1.metaClass.abc = newClosure    


def cl = new Class1()
//Before edit
//For the sake of simplicity we are going to use & for the method
//clos = cl.abc 
closs = cl.&abc
clos.delegate = this
clos()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号