好吧,我想将一个方法保存到var中以便以后调用它。我想要这样的东西:
class A {
def sayHello() {
"Hello"
}
}
def a = new A()
def sayHelloMethod = a.sayHello
def result = sayHelloMethod()
有办法做到这一点吗?
答案 0 :(得分:7)
我刚发现方法指针运算符(。&)可用于存储对变量中方法的引用。
class A {
def sayHello() {
"Hello"
}
}
def a = new A()
def sayHelloMethod = a.&sayHello
assert a.sayHello() == sayHelloMethod()
答案 1 :(得分:0)
你可以这样做:
class A {
def sayHello() {
"Hello"
}
}
def a = new A()
def sayHelloClosure = { a.sayHello }
def result = sayHelloClosure.call()