Sub topic 6
Invoking methods and unwrapping InvocationTargetException
This chapter assumes you can already get a Class object and list its members, as covered in the earlier chapters. You should also be comfortable with checked exceptions and try/catch. Here you will call methods by name, learn how arguments and return values behave, and handle the exception wrapping that surprises most people the first time.
Finding the method to call
java.lang.reflect.Method represents one method of a class. You get one from a Class object with two pairs of lookup calls:
getMethod(String name, Class<?>... parameterTypes)finds a public method, including public methods inherited from superclasses and interfaces.getDeclaredMethod(String name, Class<?>... parameterTypes)finds any method declared in that class itself, whatever its access level, but it does not search superclasses.
The lookup key is the name plus the exact parameter types. Overloads are told apart only by those types, so you must pass them. getMethod("greet", String.class) finds greet(String). It does not find greet(Object), because the match is exact, not "assignable".
If nothing matches, you get a NoSuchMethodException. This is a checked exception, and it is the most common failure at this step. Typical causes are a typo in the name, a wrong parameter type, or using getMethod for a non-public method.
A primitive parameter needs a primitive class literal. A method void setAge(int age) is found with int.class, not Integer.class.
Calling the method with invoke
Once you have a Method, call it with invoke(Object target, Object... args). The first argument is the object the method runs on. The rest are the method's arguments.
import java.lang.reflect.Method;
class Calculator {
public int add(int a, int b) {
return a + b;
}
public static int square(int x) {
return x * x;
}
public void log(String message) {
System.out.println("log: " + message);
}
}
public class InvokeBasics {
public static void main(String[] args) throws Exception {
Calculator calc = new Calculator();
Method add = Calculator.class.getMethod("add", int.class, int.class);
Object sum = add.invoke(calc, 2, 3);
System.out.println(sum);
Method square = Calculator.class.getMethod("square", int.class);
System.out.println(square.invoke(null, 7));
Method log = Calculator.class.getMethod("log", String.class);
Object result = log.invoke(calc, "hello");
System.out.println(result);
}
}This prints 5, 49, log: hello, and null. Several rules show up in that output:
- Return values are boxed.
invokereturnsObject, so theintresult ofaddarrives as anInteger. You cast or unbox it yourself. - Arguments are boxed too, then unwrapped. You pass
2and3, and the runtime converts them back tointfor the call. It also allows widening, so anIntegerargument can be passed to alongparameter. - Static methods ignore the target. Pass
nullas the first argument, as done forsquare. If you pass an object, it is ignored. - A
voidmethod returnsnull. You cannot tell this apart from a method that returnednull, so checkmethod.getReturnType()if it matters.
Varargs and the invoke signature
invoke itself is a varargs method, which creates two traps.
First, a target method that takes an array or varargs parameter takes that array as a single argument. For static String join(String... parts), the parameter type is String[].class, and you must pass one array:
Method join = Util.class.getMethod("join", String[].class);
join.invoke(null, (Object) new String[] { "a", "b" });Without the (Object) cast, the compiler spreads your String[] across invoke's own varargs, and the call fails with IllegalArgumentException: wrong number of arguments. The cast tells the compiler that the array is one argument.
Second, the wrong argument count or type also gives IllegalArgumentException. This one is unchecked, so the compiler will not warn you.
The exception model
A reflective call can fail in several distinct ways, and each has its own exception. Knowing which stage failed tells you where to look.
| Exception | Checked | Stage | Meaning |
|---|---|---|---|
| `NoSuchMethodException` | Yes | Lookup | No method with that name and parameter types. |
| `IllegalAccessException` | Yes | Invoke | The caller may not access the method, for example a private one. |
| `IllegalArgumentException` | No | Invoke | Wrong target type, argument count, or argument type. |
| `NullPointerException` | No | Invoke | Target is `null` for an instance method. |
| `InvocationTargetException` | Yes | Invoke | The method ran and itself threw an exception. |
The first four are problems with how you made the call. The last one is different. The call was valid, the method ran, and the method's own code threw.
Why InvocationTargetException exists
Suppose a method throws IllegalStateException. If invoke let that exception escape directly, you could not tell whether the failure came from the method body or from the reflection machinery. An IllegalArgumentException might mean you passed bad arguments, or it might mean the method threw one deliberately.
Java solves this by wrapping. Anything thrown from inside the invoked method is caught and rethrown as an InvocationTargetException, a checked exception. The original is stored inside it. Your own reflection errors stay unwrapped, so the two cases are always distinguishable.
Unwrapping the cause
The wrapped exception is available from getCause(). (There is also an older getTargetException() that returns the same object.) Here is the pattern from the chapter's example:
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);
}
}
}The output is Target threw: java.lang.IllegalStateException: boom. If you printed e itself, you would see only java.lang.reflect.InvocationTargetException with no message, which hides the real problem. A frequent bug in reflective code is logging the wrapper and never the cause.
Rethrowing sensibly
What you do after catching depends on your design. Callers of a reflective utility usually want the original exception, as if the call had been direct. Three options are common:
- Rethrow unchecked causes, wrap the rest. If the cause is a
RuntimeExceptionor anError, rethrow it as is. Otherwise wrap it in your own exception. - Wrap everything in your own exception type. Pass the cause along so the stack trace is preserved.
- Handle specific causes. Test with
instanceofand react to the ones you expect.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class Task {
public void run() {
throw new UnsupportedOperationException("not ready");
}
}
public class Rethrow {
static Object call(Method m, Object target, Object... args) {
try {
return m.invoke(target, args);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
}
if (cause instanceof Error) {
throw (Error) cause;
}
throw new IllegalStateException("Checked exception from " + m.getName(), cause);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Cannot access " + m.getName(), e);
}
}
public static void main(String[] args) throws Exception {
Method run = Task.class.getMethod("run");
try {
call(run, new Task());
} catch (UnsupportedOperationException e) {
System.out.println("Caught directly: " + e.getMessage());
}
}
}The helper makes the reflective call behave like a normal one for unchecked exceptions. Callers catch UnsupportedOperationException and never see the wrapper.
Edge cases
- Checked exceptions inside the target. A method declared
throws IOExceptionthat throws it will deliver anInvocationTargetExceptionwhose cause is theIOException. The compiler cannot check this for you, so handle it in yourcatch. - The cause can be
null. In ordinary use it is not, but defensive code should not assume the cause exists. - Stack traces have two parts. The wrapper's trace shows the reflection call path. The cause's trace shows where the target method actually failed. Read the cause's trace first.
- Inherited and overridden methods. Invoking a
Methodfound on a superclass or interface still uses virtual dispatch. If the target object's class overrides the method, the override runs. - Wrong target type. Passing an object that is not an instance of the declaring class gives
IllegalArgumentException, not aClassCastException. - Private methods.
getDeclaredMethodfinds them, butinvokethrowsIllegalAccessExceptionuntil you callsetAccessible(true). The next chapter covers when that works and when the module system blocks it.
Summary of the working model
A reflective call has two phases. Lookup uses a name and exact parameter types, and fails with NoSuchMethodException. Invocation takes a target and arguments, boxes and unboxes values, and fails with IllegalAccessException or IllegalArgumentException if you misuse it. Anything the method itself throws is wrapped in InvocationTargetException, and getCause() gives you the real error.
Exercise
A method public int parse(String s) throws NumberFormatException when given "abc". You call it with Method.invoke. Which exception does your code receive, how do you get the NumberFormatException, and why is this different from calling parse("abc") directly?
Show answer
Your code receives an InvocationTargetException. Call getCause() on it to get the NumberFormatException. Reflection wraps every exception thrown by the invoked method so that it can be told apart from errors in the reflective call itself, such as IllegalArgumentException for bad arguments. A direct call has no such ambiguity, so the NumberFormatException would propagate as is.
Exercise
Why does Util.class.getMethod("join", String[].class).invoke(null, new String[] {"a", "b"}) fail with IllegalArgumentException, and how do you fix it?
Show answer
The compiler treats the String[] as the varargs array of invoke, so the target method receives two arguments, "a" and "b", instead of one array. Cast the array to Object: invoke(null, (Object) new String[] {"a", "b"}). This makes the array a single argument.