Course contentsShow
← Java
Lesson 2333 of 2,87045. Reflection APIFree lesson

Getting Methods with getMethods()

Retrieve all public methods, including inherited ones, as an array of Method objects from a class.

What You'll Learn

You'll learn how to retrieve all public methods (including inherited ones) from a class using the Reflection API's getMethods() method.

Understanding getMethods()

When you need to inspect what public methods a class offers—both its own and those it inherits from parent classes and interfaces—the Class object provides the getMethods() method. This returns an array of Method objects representing every public method accessible on instances of that class.

Think of it like getting a complete directory of every public operation you can perform on an object, including capabilities it inherited from its ancestors.

How It Works

The getMethods() method is called on a Class object and returns a Method[] array:

Class<?> clazz = String.class;
Method[] methods = clazz.getMethods();

System.out.println("Total public methods: " + methods.length);

// Display first few method names
for (int i = 0; i < Math.min(5, methods.length); i++) {
    System.out.println(methods[i].getName());
}

This will show you methods like charAt, length, substring, and many others—including methods inherited from Object like toString() and equals().

What Gets Included

  • All public methods declared directly in the class
  • Public methods inherited from superclasses (like Object)
  • Public methods from interfaces the class implements
  • Does NOT include private, protected, or package-private methods

Practical Example

Class<?> clazz = Class.forName("java.util.ArrayList");
Method[] methods = clazz.getMethods();

// Count methods starting with "add"
int count = 0;
for (Method m : methods) {
    if (m.getName().startsWith("add")) {
        count++;
    }
}
System.out.println("Methods starting with 'add': " + count);

Key Takeaway: Use getMethods() to retrieve an array of all public methods available on a class, including those inherited from superclasses and interfaces—perfect for discovering a class's complete public API at runtime.