Source Code : Invoke a method using Method class

Java Is Open Source Programming Language You Can Download From Java and Java Libraries From http://www.oracle.com. Click Here to download
We provide this code related to title for you to solve your developing problem easily. Libraries which is import in this program you can download from http://www.oracle.com. Click Here or search from google with Libraries Name you get jar file related it

Invoke a method using Method class

        
 
import java.lang.reflect.Method;

public class Main {
  public static void main(String[] args) throws Exception {
    MyClass object = new MyClass();
    Class clazz = object.getClass();

    Method method = clazz.getMethod("add", new Class[] { int.class, int.class });
    Object result = method.invoke(object, new Object[] { 10, 10 });
    System.out.println("Result = " + result);

    method = clazz.getMethod("multiply", new Class[] { int.class, int.class });
    result = method.invoke(object, new Object[] { 10, 10 });
    System.out.println("Result = " + result);

  }

}
class MyClass{

  public int add(int numberA, int numberB) {
    return numberA + numberB;
  }

  public int multiply(int numberA, int numberB) {
    return numberA * numberB;
  }

  public double div(int numberA, int numberB) {
    return numberA / numberB;
  }
}
 

   
    
    
    
    
    
    
    
  

Thank with us