Convert string into a function call
Sure, you can use globals
:
func_to_run = globals()[ran_test_opt]
func_to_run()
Or, if it is in a different module, you can use getattr
:
func_to_run = getattr(other_module, ran_test_opt)
func_to_run()
How to turn a string into a method call?
Object#send
>> a = "class"
>> "foo".send(a)
=> String
>> a = "reverse"
>> "foo".send(a)
=> "oof"
>> a = "something"
>> "foo".send(a)
NoMethodError: undefined method `something' for "foo":String
How to turn a String into a JavaScript function call?
Seeing as I hate eval, and I am not alone:
var fn = window[settings.functionName];
if(typeof fn === 'function') {
fn(t.parentNode.id);
}
Edit: In reply to @Mahan's comment:
In this particular case, settings.functionName
would be "clickedOnItem"
. This would, at runtime translate var fn = window[settings.functionName];
into var fn = window["clickedOnItem"]
, which would obtain a reference to function clickedOnItem (nodeId) {}
. Once we have a reference to a function inside a variable, we can call this function by "calling the variable", i.e. fn(t.parentNode.id)
, which equals clickedOnItem(t.parentNode.id)
, which was what the OP wanted.
More full example:
/* Somewhere: */
window.settings = {
/* [..] Other settings */
functionName: 'clickedOnItem'
/* , [..] More settings */
};
/* Later */
function clickedOnItem (nodeId) {
/* Some cool event handling code here */
}
/* Even later */
var fn = window[settings.functionName];
/* note that settings.functionName could also be written
as window.settings.functionName. In this case, we use the fact that window
is the implied scope of global variables. */
if(typeof fn === 'function') {
fn(t.parentNode.id);
}
Convert string into a function call withing the same class
Don't use globals()
(the functions are not in the global symbol table), just use getattr
:
ran_test_func = getattr(self, ran_test_opt)
How to convert String to Function in Java?
What you need is an engine/library that can evaluate expressions, defined as string at execution time. If you wrap the evaluation code into function call (e.g. lambda function), you will get what you need.
Option 1: You can use exp4j. exp4j is a small footprint library, capable of evaluating expressions and functions at execution time. Here is an example:
Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
.variables("x", "y")
.build()
.setVariable("x", 2.3)
.setVariable("y", 3.14);
double result = e.evaluate();
Option 2: You can use the Java's script engine. You can use it to evaluate expressions defined, for example, in JavaScript:
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval("sin(1.25)");
Option 3: Compile to native Java. With this approach, you use template to generate .java file with a class that contains your expression. Than you call the Java compiler. This approach has the drawback that has some complexity in the implementation and some initial latency (until the class is compiled), but the performance is the best. Here are some links to explore:
- Create dynamic applications with javax.tools
- In particular javax.tools.Compiler
Note of Caution Whatever approach you chose, have in mind that you need to think about the security. Allowing the user to enter code which can be evaluated without security restrictions could be very dangerous.
Java, how to convert a string to class and call its static method?
To create new instance you need to do the following
Class c = Class.forName("Item");
Item i = (Item)c.newInstance();
If you want to invoke static method you just call it on class instead of instance
Item.test();
Or you can use reflection without directly reference to class
Class c = Class.forName("Item");
Method method = c.getMethod("test");
method.invoke(null);
I have a string whose content is a function name, how to refer to the corresponding function in Python?
Since you are taking user input, the safest way is to define exactly what is valid input:
dispatcher={'add':add}
w='add'
try:
function=dispatcher[w]
except KeyError:
raise ValueError('invalid input')
If you want to evaluate strings like 'add(3,4)'
, you could use safe eval:
eval('add(3,4)',{'__builtins__':None},dispatcher)
eval
in general could be dangerous when applied to user input. The above is safer since __builtins__
is disabled and locals
is restricted to dispatcher
. Someone cleverer than I might be able to still cause trouble, but I couldn't tell you how to do it.
WARNING: Even eval(..., {'__builtins__':None}, dispatcher)
is unsafe to be applied to user input. A malicious user could run arbitrary functions on your machine if given the opportunity to have his string evaluated by eval
.
Related Topics
Difference Between Gemfile and Gemfile.Lock in Ruby on Rails
Ignoring Gem Because Its Extensions Are Not Built
How to Group by Day Instead of Date
In Ruby Why Won't 'Foo = True Unless Defined(Foo)' Make the Assignment
Mavericks, Rbenv, Your Ruby Version Is 2.0.0, But Your Gemfile Specified 2.1.1
How to Intercept Method Call in Ruby
Extract Single String from HTML Using Ruby/Mechanize (And Nokogiri)
Method and Variable Name Is the Same
How to Use Double Brackets in a Regular Expression
Looping in a Spiral Outside-In
Has Anyone Tried Installing Ruby & Rubygems from Source on Ubuntu (Preferably Ubuntu 9)
Can't Install Rails on MAC Os Catalina
How to Remove Lines of Data in the Middle of a Text File with Ruby
Find the Newest Record in Rails 3
How Would You Parse a Url in Ruby to Get the Main Domain
Uninstalling All Gems Ruby 2.0.0
How to Access a Variable Defined in a Ruby File I Required in Irb