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();
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.
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.
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.
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. } }
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.
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