CodeBlanks Logo Icon CodeBlanks

getMethods

Learn method listing with getMethods.

Finding methods with getMethods

Class.getMethods() returns all public methods of a class, including inherited ones (for example from Object). Each method is a Method object.

Example: Method[] methods = String.class.getMethods(). In the returned array, m.getName() gives the method name, m.getReturnType() the return type, and m.getParameterTypes() the parameter types. To get only the class's own methods use getDeclaredMethods.

Inspecting a Method

A Method object carries plenty of information. getName returns the name, getReturnType the return type, getParameterTypes the parameter types.

Example: m.getName() and m.getParameterCount(). These methods let you discover a class's interface at runtime. A framework can learn which methods take which parameters and call them accordingly; this is a key tool in annotation processing and dependency injection.

Practice Find the length method of String

Find the length method with String.class.getMethod("length"). Print its name using getName() with System.out.println. Add throws NoSuchMethodException to main.

Starter code

Main.java
import java.lang.reflect.Method;

// Find the length method with String.class.getMethod
// Get its name with getName
// Add throws NoSuchMethodException and print

Sample solution

Main.java
public class StringMethods {
    public static void main(String[] args) throws NoSuchMethodException {
        Method m = String.class.getMethod("length");
        System.out.println(m.getName());
    }
}

Expected output

length

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which method returns public methods, including inherited?

  • getFields
  • getConstructors
  • getMethods Correct answer
  • getClasses

Explanation: getMethods returns public methods.

2 Find a single method with getMethod

Question
Method m = clazz.____("length");
Answer
Method m = clazz.getMethod("length");

Explanation: getMethod finds one method by name.

3 Match the Method methods

Term Meaning
getMethods Public methods
getName Method name
getReturnType Return type
getParameterTypes Parameter types

All lessons in Advanced