Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Call method using its name? [duplicate]

Tags:

c#

.net

I have an object with some methods and I want to call a method using the method name as string only.

object obj;
obj.method();
like image 513
Amged Avatar asked Sep 09 '11 01:09

Amged


People also ask

Can two classes have method with same name?

For convenience, Java allows you to write more than one method in the same class definition with the same name. For example, you can have two methods in ShoppingCart class named computeCost. Having two or more methods named the same in the same class is called overloading.

Can methods have the same name within the same class?

Typically, a method has a unique name within its class. However, a method might have the same name as other methods due to method overloading.

How do you call the same method in Java?

To call a method in Java, simply write the method's name followed by two parentheses () and a semicolon(;). If the method has parameters in the declaration, those parameters are passed within the parentheses () but this time without their datatypes specified.

How do you call one method from another?

Method2(); // Method being called. } // Method definition to call in another Method public static void Method1() { System. out. println("Hello World!"); } // Method definition performing a Call to another Method public static void Method2() { Method1(); // Method being called. } }


1 Answers

Given a method MethodName with the signature void MethodName(int num), it would be done something like:

   MethodInfo method = obj.GetType().GetMethod("MethodName", 
         BindingFlags.Public|BindingFlags.Instance)
   method.Invoke(obj, 4) // void method

Hope this helps.

like image 69
x0n Avatar answered Sep 18 '22 21:09

x0n