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:
- The exact method name as a
String - The parameter types as
Classobjects (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")— findstoString()with no parametersgetMethod("substring", int.class)— findssubstring(int)getDeclaredMethod("setName", String.class)— finds private or publicsetName(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.