Call methods of an object using reflection in Java

Java 8Object Oriented ProgrammingProgramming

The methods of an object can be called using the java.lang.Class.getDeclaredMethods() method. This method returns an array that contains all the Method objects with public, private, protected and default access. However, the inherited methods are not included.

Also, the getDeclaredMethods() method returns a zero length array if the class or interface has no methods or if a primitive type, array class or void is represented in the Class object.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.lang.reflect.Method;
class ClassA {
   private String name = "John";
   public String returnName() {
      return name;
   }
}
public class Demo {
   public static void main(String[] args) throws Exception {
      Class c = ClassA.class;
      Method[] methods = c.getDeclaredMethods();
      ClassA obj = new ClassA();
      for (Method m : methods) {
         Object result = m.invoke(obj, new Object[0]);
         System.out.println(m.getName() + ": " + result);
      }
   }
}

Output

returnName: John
raja
Published on 09-Jan-2019 11:57:00
Advertisements