Jared
Jared

Reputation: 39893

call name of method contained in a string

How can I call a method based on the value of a string in Groovy? For example instead of

switch (val) {
case "one":
    Obj.one()
    break
case "two":
    Obj.two()
    break
}

I’d like to do something like obj.val where val contains either "one" or "two" instead of a case statement.

Upvotes: 44

Views: 23571

Answers (1)

Michael Borgwardt
Michael Borgwardt

Reputation: 346476

Dynamic method invocation looks like this

obj."$val"()

Upvotes: 93

Related Questions