【问题标题】:How to add a new closure to a class in groovy如何在 groovy 中为类添加新的闭包
【发布时间】:2010-12-11 05:26:37
【问题描述】:

来自Snipplr

好的,这里是脚本代码,在 cmets 中是问题和抛出的异常

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()
}

//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()

【问题讨论】:

    标签: groovy metaprogramming metaclass expandometaclass


    【解决方案1】:

    好的,已经完成了,这不是一种花哨的方式,但我有解决方案....是的!

    将属性创建为对象,然后分配闭包

    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()
    

    【讨论】:

    • 好的,它可以工作,但我需要“实现” abc 作为所有实例的闭包......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 2020-02-10
    相关资源
    最近更新 更多