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.
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.
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.
Dynamic method invocation looks like this
obj."$val"()
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