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


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

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements