Sub topic 6
Invoking methods and unwrapping InvocationTargetException
This chapter assumes you can already get a Class object and look up members with getMethod, as covered in the earlier chapters. You should also be comfortable with checked exceptions and try/catch.
Finding and calling a method
Method.invoke calls a method that you looked up by name at runtime. The first argument is the target object. The remaining arguments are the method's parameters.
Two lookup methods exist, and they differ in scope:
getMethod(name, paramTypes...)finds public methods, including inherited ones.getDeclaredMethod(name, paramTypes...)finds any method declared on that class, including private ones, but not inherited ones.
You must pass the parameter types as Class objects. Methods can be overloaded, so the name alone does not identify one.
import java.lang.reflect.Method;
class Person {
private String name = "Ada";
public String greet(String other) {
return "Hi " + other + ", I am " + name;
}
}
public class CallDemo {
public static void main(String[] args) throws Exception {
Method greet = Person.class.getMethod("greet", String.class);
Object result = greet.invoke(new Person(), "Linus");
System.out.println(result);
}
}invoke returns Object. A primitive result is boxed, so an int method returns an Integer. A void method returns null. For a static method, pass null as the target.
Exceptions you must handle
Reflection adds its own checked exceptions on top of whatever the target method declares:
| Exception | Typical cause |
|---|---|
| `NoSuchMethodException` | The name or parameter types do not match any method. |
| `IllegalAccessException` | The method is not accessible to the caller. |
| `IllegalArgumentException` | The target object or arguments have the wrong type or count. |
| `InvocationTargetException` | The invoked method itself threw an exception. |
The last one is the one that surprises people.
Why InvocationTargetException exists
If the target method throws, invoke does not rethrow that exception directly. It wraps it in an InvocationTargetException. The wrapper lets you tell apart "the call failed because of reflection" from "the call worked and the method then failed".
The wrapper's own message is usually empty. The useful information is in getCause().
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class Risky {
public void fail() {
throw new IllegalStateException("boom");
}
}
public class UnwrapDemo {
public static void main(String[] args) throws Exception {
Method m = Risky.class.getMethod("fail");
try {
m.invoke(new Risky());
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
System.out.println("Target threw: " + cause);
}
}
}This prints Target threw: java.lang.IllegalStateException: boom.
Rethrowing the real error
Often you want callers to see the original exception, not the wrapper. A common pattern unwraps it and rethrows unchecked exceptions and errors as they are.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Invoker {
static Object call(Method m, Object target, Object... args) throws Exception {
try {
return m.invoke(target, args);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof Exception) {
throw (Exception) cause;
}
if (cause instanceof Error) {
throw (Error) cause;
}
throw e;
}
}
}Common mistakes
- Catching only
Exceptionand printinge.getMessage(). For anInvocationTargetExceptionthis is usuallynull, which hides the real failure. - Forgetting that
getMethoddoes not find private methods. UsegetDeclaredMethodandsetAccessible(true), as covered in the access chapter. - Passing the wrong argument types. Boxing and widening are applied, but an
Integerwill not convert to aString.
Exercise
A method called through Method.invoke throws IllegalArgumentException("bad input") from its own body. Which exception does the caller of invoke catch, and how does it get "bad input"?
Show answer
The caller catches InvocationTargetException, because invoke wraps anything thrown by the target method. It reads the original exception with e.getCause() and then calls getMessage() on it to get "bad input". An IllegalArgumentException thrown directly by invoke itself would instead mean the reflective call had a wrong target or arguments.