How can we call a method which name is string at runtime. Can anyone show me how to do that in Java and C.
In java it can be done through the reflection api.
Have a look at Class.getMethod(String methodName, Class... parameterTypes)
.
A complete example (of a non-static method with an argument) would be:
import java.lang.reflect.*;
public class Test {
public String methodName(int i) {
return "Hello World: " + i;
}
public static void main(String... args) throws Exception {
Test t = new Test();
Method m = Test.class.getMethod("methodName", int.class);
String returnVal = (String) m.invoke(t, 5);
System.out.println(returnVal);
}
}
Which outputs:
Hello World: 5
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