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

Java 8Object Oriented ProgrammingProgramming

The java.lang.reflect.Method class provides information about, and access to, a single method on a class or interface. The reflected method may be a class method or an instance method (including an abstract method). A Method permits widening conversions to occur when matching the actual parameters to invoke with the underlying method's formal parameters, but it throws an IllegalArgumentException if a narrowing conversion would occur.

You can invoke the method using the class named method of the package java.lang.reflect. The constructor of this class accepts the method name in the form of a string. And you can invoke this method using the invoke() method.

Example

import java.lang.reflect.Method;

public class DemoTest {
   private void sampleMethod(){
      System.out.println("hello");
   }
}
public class SampleTest {
   public static void main(String args[]) throws Exception{
      Class c = Class.forName("DemoTest");
      Object obj = c.newInstance();
      
      Method method = c.getDeclaredMethod("sampleMethod", null);
      method.setAccessible(true);
      method.invoke(obj, null);
   }
}
raja
Published on 08-Jan-2018 14:29:07
Advertisements