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

Getting a Specific Method by Name and Parameters

Learn getMethod() and getDeclaredMethod() to retrieve a specific method by its signature for invocation.

Getting a Specific Method by Name and Parameters

You'll learn how to retrieve a single, specific method from a class by providing its exact name and parameter types.

The Problem with Bulk Retrieval

You've already seen how to get all methods using getMethods() or getDeclaredMethods(), but what if you need just one specific method? Searching through arrays is inefficient when you know exactly which method you want.

Two Targeted Retrieval Methods

Java's Class object offers two methods for pinpoint method retrieval:

getMethod(String name, Class<?>... parameterTypes)

Retrieves a public method by name and parameter signature. Searches the class and all inherited methods (from superclasses and interfaces).

getDeclaredMethod(String name, Class<?>... parameterTypes)

Retrieves any method declared directly in this class—public, private, protected, or package-private—but does not search superclasses.

How It Works

Both methods require:

  1. The exact method name as a String
  2. The parameter types as Class objects (in order)

Think of it like a phone book search: You need both the last name (method name) and the street address (parameter types) to find the exact person—just a name isn't enough when multiple methods share it.

For a no-argument method, pass no parameter types. For methods with parameters, provide each parameter's class:

  • getMethod("toString") — finds toString() with no parameters
  • getMethod("substring", int.class) — finds substring(int)
  • getDeclaredMethod("setName", String.class) — finds private or public setName(String)

These methods throw NoSuchMethodException if no matching method exists with that exact signature.

Key Takeaway:
Use getMethod() or getDeclaredMethod() with exact method name and parameter type classes to retrieve a specific method for later invocation—eliminating the need to search through method arrays.