Search

Dark theme | Light theme

March 4, 2010

Groovy Goodness: Invoke Methods Dynamically

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]}"()