Groovy : 如何将闭包作为参数传递以执行 class 中的方法
Groovy : how to pass closure as parameter to execute the methods inside the class
我需要在 class 和 "closure way" 中传递要执行的方法列表,请参阅下面的代码
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()
方法识别为 class 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"
}
}
委托有机会响应在闭包内部进行的方法调用。将委托设置为 this
将导致对 m1()
的调用被分派到 A
的实例。您可能还对设置闭包的 resolveStrategy
属性 感兴趣。 resolveStrategy
的有效值为 Closure.DELEGATE_FIRST
、Closure.OWNER_FIRST
、Closure.DELEGATE_ONLY
、Closure.OWNER_ONLY
。 owner
是创建闭包的东西,不能更改。 delegate
可以赋给任何对象。当闭包进行方法调用时,方法可能由 owner
或 delegate
处理,而 resolveStrategy
在决定使用哪个方面发挥作用。我认为名称 DELEGATE_ONLY
、OWNER_ONLY
、DELEGATE_FIRST
和 OWNER_FIRST
是不言自明的。如果您需要更多信息,请告诉我。
希望对您有所帮助。
我需要在 class 和 "closure way" 中传递要执行的方法列表,请参阅下面的代码
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()
方法识别为 class 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"
}
}
委托有机会响应在闭包内部进行的方法调用。将委托设置为 this
将导致对 m1()
的调用被分派到 A
的实例。您可能还对设置闭包的 resolveStrategy
属性 感兴趣。 resolveStrategy
的有效值为 Closure.DELEGATE_FIRST
、Closure.OWNER_FIRST
、Closure.DELEGATE_ONLY
、Closure.OWNER_ONLY
。 owner
是创建闭包的东西,不能更改。 delegate
可以赋给任何对象。当闭包进行方法调用时,方法可能由 owner
或 delegate
处理,而 resolveStrategy
在决定使用哪个方面发挥作用。我认为名称 DELEGATE_ONLY
、OWNER_ONLY
、DELEGATE_FIRST
和 OWNER_FIRST
是不言自明的。如果您需要更多信息,请告诉我。
希望对您有所帮助。