Java Reflection method invoke a method

Introduction

The reflection API also allows us to invoke a method for both static and non-static.

This is done using Method.invoke() method which looks like this:

public Object invoke(Object obj, Object... args) 

The first argument is the object instance or null for static method.

The second argument, an array of objects, is the method's parameters if there is any.

This argument array may be of length 0 or null or absent if the number of formal parameters required by the underlying method is 0.

The following program invokes the method length() on a String object.

import java.lang.reflect.Method;

public class Main {
   public static void main(String args[]) throws Exception {
      String s = new String("Java");
      Class c = s.getClass();//from w w  w.j a  va  2  s  .c  o  m
      Method m = c.getDeclaredMethod("length");
      System.out.println("The length of " + s + " is " + m.invoke(s));
   }
}



PreviousNext

Related