Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically invoking any function by passing function name as string

How do I automate the process of getting an instance created and its function executed dynamically?

Thanks

Edit: Need an option to pass parameters too. Thanks

like image 638
Josh Avatar asked Apr 29 '09 06:04

Josh


People also ask

How can I call a function given its name as 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 dynamic function name?

To use dynamic function name in JavaScript, we can create an object with the function name. const name = "myFn"; const fn = { [name]() {} }[name]; to set the fn variable to a function with the name name . We put the name method in the object and then we get the method with [name] .

How do you call a JavaScript function name?

The JavaScript call() Method The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.

How do you call a function name?

Define a function named "myFunction", and make it display "Hello World!" in the <p> element. Hint: Use the function keyword to define the function (followed by a name, followed by parentheses). Place the code you want executed by the function, inside curly brackets. Then, call the function.


1 Answers

Do you just want to call a parameterless constructor to create the instance? Is the type specified as a string as well, or can you make it a generic method? For example:

// All error checking omitted. In particular, check the results // of Type.GetType, and make sure you call it with a fully qualified // type name, including the assembly if it's not in mscorlib or // the current assembly. The method has to be a public instance // method with no parameters. (Use BindingFlags with GetMethod // to change this.) public void Invoke(string typeName, string methodName) {     Type type = Type.GetType(typeName);     object instance = Activator.CreateInstance(type);     MethodInfo method = type.GetMethod(methodName);     method.Invoke(instance, null); } 

or

public void Invoke<T>(string methodName) where T : new() {     T instance = new T();     MethodInfo method = typeof(T).GetMethod(methodName);     method.Invoke(instance, null); } 
like image 52
Jon Skeet Avatar answered Sep 22 '22 13:09

Jon Skeet