In Groovy we can invoke a method just like in Java: we simply type the name of the method in our code. But what if we want to invoke a method name, but we don't know the name yet when we write the code, but we do know it at runtime? We can use the Reflection API for example to invoke the method, but in Groovy it can be shorter. In Groovy we can use a variable value for method invocation with a GString. The GString is evaluated at runtime and the result must be the method name we want to invoke.
class Simple {
def hello(value) {
"Hello $value, how are you?"
}
def goodbye() {
"Have a nice trip."
}
}
def s = new Simple()
def methods = ['hello', 'goodbye']
assert 'Hello mrhaki, how are you?', s."$methods[0]"('mrhaki')
assert 'Have a nice trip.', s."$methods[1]"
3 comments:
Good to see you are posting again - I've missed your daily tidbits of Groovy!
Hi, thanks. I will be posting more regularly from now on. Probably each workday.
It was interesting to read this article and I hope to read a new article about this subject in your site in the near time.
Post a Comment