Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

If I have two variables:

Object obj; String methodName = "getName"; 

Without knowing the class of obj, how can I call the method identified by methodName on it?

The method being called has no parameters, and a String return value. It's a getter for a Java bean.

like image 698
brasskazoo Avatar asked Oct 02 '08 05:10

brasskazoo


People also ask

How do we invoke a method in Java?

To call a method in Java, write the method's name followed by two parentheses () and a semicolon; The process of method calling is simple.

How do you call a string method from the main method in Java?

Call a Method Inside main , call the myMethod() method: public class Main { static void myMethod() { System.out.println("I just got executed!"); } public static void main(String[] args) { myMethod(); } } // Outputs "I just got executed!"


2 Answers

Coding from the hip, it would be something like:

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) { ... } 

Again, leave out the arguments in .invoke, if you don't have any. But yeah. Read about Java Reflection

like image 104
Henrik Paul Avatar answered Sep 25 '22 20:09

Henrik Paul


Use method invocation from reflection:

Class<?> c = Class.forName("class name"); Method method = c.getDeclaredMethod("method name", parameterTypes); method.invoke(objectToInvokeOn, params); 

Where:

  • "class name" is the name of the class
  • objectToInvokeOn is of type Object and is the object you want to invoke the method on
  • "method name" is the name of the method you want to call
  • parameterTypes is of type Class[] and declares the parameters the method takes
  • params is of type Object[] and declares the parameters to be passed to the method
like image 22
Owen Avatar answered Sep 23 '22 20:09

Owen