Groovy:如何传递closure作为参数来执行类中的方法

Rod*_*ues 3 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"
}
Run Code Online (Sandbox Code Playgroud)

当我评论m1()输出是

  before
  before execute method m1
  after execute method m1
  after
Run Code Online (Sandbox Code Playgroud)

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

因此,它不承认该m1()方法作为方法class A

Jef*_*own 6

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

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"
    }
}
Run Code Online (Sandbox Code Playgroud)

委托有机会响应在闭包内部进行的方法调用.将委托设置为this将导致将调用m1()分派给实例A.您可能也有兴趣设置resolveStrategy闭包的属性.有效值resolveStrategyClosure.DELEGATE_FIRST,Closure.OWNER_FIRST,Closure.DELEGATE_ONLY,Closure.OWNER_ONLY.该owner是创建关闭和不能改变的东西.的delegate可分配的任何对象.当闭包进行方法调用时,方法可以由owner或处理,delegate并且resolveStrategy在决定使用哪个方法时起作用.名称DELEGATE_ONLY,OWNER_ONLY,DELEGATE_FIRSTOWNER_FIRST我想不言自明.如果您需要更多信息,请告诉我们.

我希望有所帮助.

  • @PlexQ“它也不能很好地与 Java 8 配合使用。” - 上面描述的所有内容都可以在 Java 8 上正常工作。您的其余评论是主观的,并不是特别有帮助。 (2认同)