Method.invoke wraps an exception thrown by the invoked method in InvocationTargetException. Lookup and access failures remain separate reflective failures.
Java reflection: separate an invoked method failure from lookup failure
Operational contract
The method looks up one fixed public operation and propagates the policy's RuntimeException as the policy failure. It leaves checked target failures wrapped, so the caller can inspect the cause without silently changing its checked-exception contract. The target class and method must be accessible under Java language and module rules. A string supplied by an untrusted caller should not select arbitrary methods. Cache a Method when the same fixed operation runs repeatedly, while still checking target compatibility.
Failure case
A shipment policy throws IllegalStateException while evaluating shipment 47. That is a policy failure, not NoSuchMethodException. Reporting only InvocationTargetException hides the meaningful cause; treating every reflective exception as retryable can repeat a rejected shipment.
Java code
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;
public class ShipmentPolicyInvocation {
public static String evaluate(Object policy, long shipmentId)
throws ReflectiveOperationException {
Objects.requireNonNull(policy);
Method method = policy.getClass().getMethod("evaluate", long.class);
try {
return (String) method.invoke(policy, shipmentId);
} catch (InvocationTargetException failure) {
Throwable target = failure.getCause();
if (target instanceof RuntimeException runtime) throw runtime;
throw failure;
}
}
}Performance and ownership cost
Looking up and invoking a method takes O(1) application space and adds reflective dispatch and boxing overhead to the policy's own work. Repeated lookup can be cached, but the cache must be scoped to class identity and class-loader lifetime.
Common Mistakes
- Do not classify a target exception as a missing method or access failure.
- Do not let arbitrary user input name a method to invoke.
- Do not ignore that Method.invoke returns Object and may require a checked cast.
Connected lessons
- Java reflection: inspect types without breaking contracts
- Java getMethod: resolve an overload by its exact parameter types
- Java trySetAccessible: handle a denied deep-reflection request
- Java MethodHandle.invokeExact: make the call-site type part of the contract
- Java runtime discovery contracts quiz
- Advanced Java
