Well, I want to save a method into a var to call it later. I want something like this:
class A {
def sayHello() {
"Hello"
}
}
def a = new A()
def sayHelloMethod = a.sayHello
def result = sayHelloMethod()
Is there a way to do this?
Groovy does its magic by intercepting all method calls on objects (both Java objects and Groovy objects) and using its ExpandoMetaClass to add the behavior. However, it can't change how pure Java code determines which method to call on a pure Java class.
In normal, non type checked, Groovy, you can write things like: The method call works because of dynamic dispatch (the method is selected at runtime). The equivalent code in Java would require to cast o to a Greeter before calling the greeting method, because methods are selected at compile time:
The equivalent Java code of above Groovy example would be: A method in Groovy does not explicitly needs to use the return keyword to return a value. The last line having an expression is considered to be returned from the method. That applies to the methods declared in a class as well. A method with void return type returns null:
For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser. There are following basic types of variable in Groovy as explained in the previous chapter −
I just found that the method pointer operator (.&) can be used to store a reference to a method in a variable.
class A {
def sayHello() {
"Hello"
}
}
def a = new A()
def sayHelloMethod = a.&sayHello
assert a.sayHello() == sayHelloMethod()
You can do:
class A {
def sayHello() {
"Hello"
}
}
def a = new A()
def sayHelloClosure = { a.sayHello }
def result = sayHelloClosure.call()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With