Class.getMethod selects a public method by name and exact parameter-type array. It does not search for the overload that would be chosen by a normal source-code call.
Java getMethod: resolve an overload by its exact parameter types
Operational contract
The lookup specifies long and int primitives, then invokes a single rate method. A Long.class parameter is not long.class. Method.invoke may box arguments during invocation, but that conversion does not change the method selected during lookup. If the requested signature is absent, NoSuchMethodException signals a contract mismatch; selecting the first method with the right name can silently call a different overload. The sample checks the result type before unboxing it.
Failure case
A pricing plugin adds rate(Long, int) beside rate(long, int). Looking up Long.class when the integration contract calls for long.class fails instead of silently choosing a different policy.
Java code
import java.lang.reflect.Method;
import java.util.Objects;
public class DepotRateLookup {
public static long cents(Object rateTable, long depotId, int parcelCount)
throws ReflectiveOperationException {
Objects.requireNonNull(rateTable);
Method rate = rateTable.getClass().getMethod("rate", long.class, int.class);
Object result = rate.invoke(rateTable, depotId, parcelCount);
if (!(result instanceof Long cents) || cents < 0)
throw new IllegalStateException("Rate must be nonnegative long cents");
return cents;
}
}Performance and ownership cost
Signature lookup and invocation add reflective overhead and O(1) application storage. For a fixed plugin API, validate and cache the selected Method at registration instead of scanning overloads on each request.
Common Mistakes
- Do not substitute Long.class for long.class in an exact lookup.
- Do not pick an overload by name alone.
- Do not assume a reflected result has the required type or valid business range.
