Get all methods including the inherited method in Java

Description

The following code shows how to get all methods including the inherited method.

Example


import java.lang.reflect.Method;
/* w ww  .j  av a  2 s.co m*/
class GetMethods {
  public int add(int numberA, int numberB) {
    return numberA + numberB;
  }

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

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

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

    Method[] methods = clazz.getMethods();
    for (Method method : methods) {
      System.out.println("Method name        = " + method.getName());
      System.out.println("Method return type = " + method.getReturnType().getName());

      Class[] paramTypes = method.getParameterTypes();
      for (Class c : paramTypes) {
        System.out.println("Param type         = " + c.getName());
      }
    }
    Method method = clazz.getMethod("add", new Class[] { int.class, int.class });
    System.out.println("Method name: " + method.getName());
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy