Passing Arguments: Varargs and Array Wrapping
You'll learn how to correctly pass arguments when invoking methods reflectively, whether they accept varargs, arrays, or no parameters at all.
The Core Challenge
When you call Method.invoke(target, args...), the second parameter itself is a varargs of type Object.... This creates a wrapping puzzle: you must pass method arguments as individual elements to invoke(), but Java will wrap them into an Object[] array for you.
The tricky part? If the method you're invoking also takes varargs or an array, you need to understand how the wrapping layers interact.
How It Works
For regular methods, pass arguments directly:
Method m = String.class.getMethod("substring", int.class, int.class);
String result = (String) m.invoke("Hello", 1, 3); // Pass 1, 3 directly
For no-argument methods, pass nothing (or an empty array):
Method m = String.class.getMethod("length");
int len = (int) m.invoke("Hello"); // No arguments needed
For methods expecting an array or varargs, you must wrap the array itself:
Method m = Arrays.class.getMethod("asList", Object[].class);
String[] data = {"a", "b", "c"};
List<?> result = (List<?>) m.invoke(null, (Object) data); // Wrap array as single Object
Without (Object) cast, Java would unwrap data and pass its elements as separate arguments—wrong!
The Mental Model
Think of invoke(target, arg1, arg2, arg3) as "unwrapping" your arguments. If your target method expects an array, you must prevent premature unwrapping by boxing the array into a single Object.
Key Takeaway:
When invoking methods reflectively, pass arguments directly to invoke(), but wrap arrays in (Object) cast if the target method expects the array itself—not its elements.