Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call name of method contained in a string

Tags:

groovy

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.

like image 688
Jared Avatar asked Aug 31 '09 14:08

Jared


People also ask

How do you call a method in a string?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.

How do you call a method from a string in Python?

Use locals() and globals() to Call a Function From a String in Python. Another way to call a function from a string is by using the built-in functions locals() and globals . These two functions return a Python dictionary that represents the current symbol table of the given source code.


1 Answers

Dynamic method invocation looks like this

obj."$val"() 
like image 159
Michael Borgwardt Avatar answered Oct 02 '22 13:10

Michael Borgwardt