常规 : how to pass closure as parameter to execute the methods inside the class

标签 groovy closures

我需要通过“闭包方式”在类中执行的方法列表,请参见下面的代码

 class A{
    def m1(){
      println "Method1"
    }

    def m2(){
      println "Method1"
    }

   def commands = { closure->
      println "before"
      closure.call()
      println "after"    
   }

}


A a = new A()
a.commands{
   println "before execute method m1"
   m1() //A need to execute m1 method of the class A
   println "after execute method m1"
}

当我评论 m1() 时,输出是

  before
  before execute method m1
  after execute method m1
  after

否则抛出异常MissingMethodException: No signature of method for method m1()

因此,它不会将m1() 方法识别为A 类

的方法

最佳答案

根据你真正想要完成的事情,你可能想要这样的东西......

class A{
    def m1(){
        println "Method1"
    }

    def m2(){
        println "Method1"
    }

    def commands(closure) {
        def c = closure.clone()
        c.delegate = this
        println "before"
        c()
        println "after"
    }
}

委托(delegate)有机会响应在闭包内部进行的方法调用。将委托(delegate)设置为 this 将导致对 m1() 的调用被分派(dispatch)到 A 的实例。您可能还对设置闭包的 resolveStrategy 属性感兴趣。 resolveStrategy 的有效值为 Closure.DELEGATE_FIRSTClosure.OWNER_FIRSTClosure.DELEGATE_ONLYClosure。 OWNER_ONLYowner 是创建闭包的人,不能更改。 delegate 可以分配给任何对象。当闭包进行方法调用时,方法可能由 ownerdelegate 处理,并且 resolveStrategy 在决定使用哪个方面发挥作用。 DELEGATE_ONLYOWNER_ONLYDELEGATE_FIRSTOWNER_FIRST 我认为这些名称是不言自明的。如果您需要更多信息,请告诉我。

希望对您有所帮助。

关于常规 : how to pass closure as parameter to execute the methods inside the class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28468175/

相关文章:

validation - 西类牙语ID:grails中的NIF,NIE,CIF验证程序

java - 如何在 eclipse 中调试 groovy 代码 (Play-Framework)

javascript - 封闭类与经典类

go - 打印闭包捕获的所有变量

docker - docker 内的 Jenkins (Jenkins)无法提取图像

Grails 查询不使用 GORM

spring - 为什么我不能让 Spring 加载时间编织工作

function - rust -将用户提供的安全功能包装到不安全的FFI功能中以进行FFI回调

javascript - 我如何将两个函数放在一起,两个函数内部都有递归

javascript - 在 Javascript 中返回 MyClass 的 ID