Invoke methods of an object using reflection in Java

Description

The following code shows how to invoke methods of an object using reflection.

Example


/*w w  w.j a  v a  2 s . c  o  m*/
import java.lang.reflect.Method;

public class Main {
  public static void main(String[] args) throws Exception {
    Class computerClass = MyClass.class;
    Method[] methods = computerClass.getDeclaredMethods();
    MyClass computer = new MyClass();
    for (Method method : methods) {
      Object result = method.invoke(computer, new Object[0]);
      System.out.println(method.getName() + ": " + result);
    }
  }
}

class MyClass {
  private String type = "type";
  public String getType() {
    return type;
  }

}

The code above generates the following result.





















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy