2017  Kodetalk | Feedback | Privacy Policy | Terms | About

How do I invoke a Java method when given the method name as a string?

I want to call a method, whose name will be given as an input

This can be done by Java Reflection

java.lang.reflect.Method method;

try {

  method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);

} catch (SecurityException e) {

  // ...

} catch (NoSuchMethodException e) {

  // ...


The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give methodName).

Then you invoke that method by calling

try {

  method.invoke(obj, arg1, arg2,...);

} catch (IllegalArgumentException e) {

} catch (IllegalAccessException e) {

} catch (InvocationTargetException e) {

leave out the arguments in .invoke, if you don't have any.

Answer is