Java Reflection: Invoking Methods and Writing Generic Array Code
Finish Java reflection: create arrays of any type with java.lang.reflect.Array, grow arrays generically like Arrays.copyOf, call methods with Method.invoke, invoke constructors with arguments, handle InvocationTargetException, and compare reflection with method handles and lambdas.
kvi5hnuCode Sprout team member9 min readOn this page
This article finishes the reflection tour with two more abilities: creating arrays whose element type is only known at runtime, and calling methods and constructors through reflective objects. Both are tools for library writers, and both have modern alternatives you should know about.
Writing Generic Array Code with java.lang.reflect.Array
The Array class in java.lang.reflect lets you create arrays dynamically. The JDK uses it, for example, in Arrays.copyOf, the method that grows a full array:
var a = new Employee[100];
. . .
// array is full
a = Arrays.copyOf(a, 2 * a.length);
Could you write that yourself, for arrays of any element type? Since every object array converts to Object[], the obvious attempt is:
public static Object[] naiveResize(Object[] a, int newLength) { // not useful
var newArray = new Object[newLength];
System.arraycopy(a, 0, newArray, 0, Math.min(a.length, newLength));
return newArray;
}
It compiles, but the result is useless to a caller holding an Employee[]. The new array was created as new Object[...], and casting it to Employee[] throws ClassCastException.
Every array object records its element type at creation. Viewing an Employee[] through an Object[] variable and casting it back is fine, because the object really is an Employee[]. An array created as Object[] stays an Object[] forever.
![naiveResize creates new Object[newLength], so the cast to String[] throws ClassCastException; resize calls Array.newInstance with the original component type, so the result really is a String[]](https://code-sprout-content.laxmi.solutions/asset/2026/11/j5u5ytnmolx7dtkg.png)
So the copy has to be created with the original's element type, which isn't known until run time. Array.newInstance does exactly that, given an element type and a length:
Object newArray = Array.newInstance(componentType, newLength);
Both inputs come from the original array: a.getClass() gives its Class, isArray() confirms it is an array, getComponentType() yields the element type (or null for non-arrays), and the static Array.getLength(a) works for every array, primitive or not. Note that the length lives in Array while the element type lives in Class; the split is historical, not meaningful.
public static Object resize(Object a, int newLength) {
Class<?> cl = a.getClass();
if (!cl.isArray()) return null;
Class<?> componentType = cl.getComponentType();
int length = Array.getLength(a);
Object newArray = Array.newInstance(componentType, newLength);
System.arraycopy(a, 0, newArray, 0, Math.min(length, newLength));
return newArray;
}
This method grows arrays of any type, not just arrays of objects:
int[] a = { 1, 2, 3, 4, 5 };
a = (int[]) resize(a, 10);
That's why the parameter is declared as Object, not Object[]. The type int[] can be converted to Object, but not to an array of objects.
More array helpers
| Method | Purpose |
|---|---|
Array.get(array, i), Array.set(array, i, value) | Read or write an element; primitives are wrapped |
Array.getInt, setInt, getDouble, … | Primitive versions for boolean, byte, char, double, float, int, long, short |
Array.getLength(array) | Length of any array |
Array.newInstance(type, length) | New one-dimensional array |
Array.newInstance(type, d1, d2, …) | New multidimensional array, such as int[2][3] |
cl.componentType() (Java 12) | Same as getComponentType() |
cl.arrayType() (Java 12) | The reverse: for String.class, returns String[].class |
Invoking Arbitrary Methods
Java has no function pointers in the C sense. Passing behavior around is normally done with interfaces and lambda expressions (next part), which the compiler can type-check. Reflection offers a lower-level route: a Method object can be called with arguments supplied at run time.
You've seen that Field.get reads a field. Similarly, the Method class has an invoke method that calls the method wrapped in the Method object:
Object invoke(Object obj, Object... args)
- The first parameter is the implicit argument (the object the method is called on).
- The remaining arguments are the explicit arguments. Since they are
Objects, primitive values are passed as wrappers. Autoboxing does that for you. - For a static method, the first argument is ignored, so pass
null.
If m1 represents Employee.getName, here's how to call it:
String n = (String) m1.invoke(omar);
If the return type is primitive, invoke returns the wrapper instead. If m2 represents getSalary, the result is a Double, which you cast and auto-unbox:
double s = (Double) m2.invoke(omar);
For a void method, invoke returns null.
Getting a Method object
You could call getDeclaredMethods and search the array for the method you want. More conveniently, call getMethod. Because methods can be overloaded, a name isn't enough: you also supply the parameter types:
Method getMethod(String name, Class<?>... parameterTypes)
For example:
Method m1 = Employee.class.getMethod("getName");
Method m2 = Employee.class.getMethod("giveRaise", double.class);
getMethod finds public methods, including inherited ones. Use getDeclaredMethod for a non-public method declared in the class itself, followed by setAccessible(true) if you need to call it from outside its access scope.
Invoking constructors with arguments
Use the same approach for constructors. Pass the parameter types to getConstructor and the argument values to newInstance:
Class<Scanner> cl = Scanner.class; // or any other class with a constructor that accepts a String
Constructor<Scanner> cons = cl.getConstructor(String.class);
Scanner in = cons.newInstance("seven bright stars tonight");
Method and Constructor both extend the abstract class Executable, which holds what they have in common (parameters, exceptions, modifiers). Since Java 17, Executable is a sealed class that permits only Method and Constructor.
What can go wrong
| Problem | Exception |
|---|---|
| No method with that name and parameter types | NoSuchMethodException (checked) |
| Method not accessible (e.g. private) | IllegalAccessException (checked) |
| Wrong number or types of arguments, or wrong implicit argument | IllegalArgumentException (unchecked) |
null implicit argument for an instance method | NullPointerException |
| The invoked method itself throws | InvocationTargetException (checked), with the original exception as its cause |
The last row is important: if the method you call throws, say, an IllegalArgumentException, you don't receive it directly. You receive an InvocationTargetException, and getCause() returns the original. That lets you tell "my reflective call was wrong" from "the called code failed". Frameworks usually unwrap the cause before reporting.
A Function Tabulator
As a demonstration, tabulate below prints x and f(x) for any static method from double to double, for instance Math.cbrt or a cube method of our own. The loop doesn't know which function it calls:
double dx = (to - from) / (n - 1);
for (double x = from; x <= to; x += dx) {
double y = (Double) f.invoke(null, x);
System.out.printf("%10.4f | %10.4f%n", x, y);
}
f is a Method, and invoke receives null as the target because a static method has none. To tabulate the cube root, look the method up by name and parameter types:
Math.class.getMethod("cbrt", double.class)
Here is everything from this article in one program:
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.*;
import java.util.Arrays;
import java.util.Locale;
import java.util.Scanner;
import java.util.function.DoubleUnaryOperator;
public class Solution {
public static void main(String[] args) throws Throwable {
// --- generic array code ---
int[] a = { 1, 2, 3 };
a = (int[]) resize(a, 10);
System.out.println(Arrays.toString(a));
String[] b = { "red", "green", "blue" };
b = (String[]) resize(b, 5);
System.out.println(Arrays.toString(b) + " " + b.getClass().getSimpleName());
try {
b = (String[]) naiveResize(b, 10);
} catch (ClassCastException e) {
System.out.println("naiveResize: ClassCastException");
}
System.out.println(String.class.arrayType().getName() + " " + int[].class.componentType());
Object grid = Array.newInstance(int.class, 2, 3); // int[2][3]
Array.setInt(Array.get(grid, 1), 2, 42);
System.out.println(Arrays.deepToString((int[][]) grid));
// --- invoking methods ---
var omar = new Employee("Omar Haddad", 52000);
Method m1 = Employee.class.getMethod("getName");
Method m2 = Employee.class.getMethod("giveRaise", double.class);
Method m3 = Employee.class.getMethod("getSalary");
String n = (String) m1.invoke(omar);
m2.invoke(omar, 10); // 10 is autoboxed into Object...
double s = (Double) m3.invoke(omar); // primitive results come back wrapped
System.out.println(n + " " + s);
// --- invoking constructors ---
Constructor<Scanner> cons = Scanner.class.getConstructor(String.class);
Scanner in = cons.newInstance("seven bright stars tonight");
System.out.println(in.next() + " " + in.next());
// exceptions thrown by the invoked method are wrapped
try {
m2.invoke(omar, -200);
} catch (InvocationTargetException e) {
System.out.println("wrapped: " + e.getCause());
}
try {
m2.invoke(omar, "ten");
} catch (IllegalArgumentException e) {
System.out.println("wrong argument type: IllegalArgumentException");
}
// --- a method "pointer" for tabulating functions ---
Method cube = Solution.class.getMethod("cube", double.class);
Method cbrt = Math.class.getMethod("cbrt", double.class);
tabulate(0, 2, 5, cube);
tabulate(1, 27, 3, cbrt);
// modern alternatives
MethodHandle mh = MethodHandles.lookup().findStatic(Math.class, "cbrt",
MethodType.methodType(double.class, double.class));
double r = (double) mh.invokeExact(10.0);
DoubleUnaryOperator f = Math::cbrt;
System.out.printf(Locale.US, "%.4f %.4f%n", r, f.applyAsDouble(10.0));
}
// works for any array, including int[]: the copy has the original's element type
public static Object resize(Object a, int newLength) {
Class<?> cl = a.getClass();
if (!cl.isArray()) return null;
Class<?> componentType = cl.getComponentType();
int length = Array.getLength(a);
Object newArray = Array.newInstance(componentType, newLength);
System.arraycopy(a, 0, newArray, 0, Math.min(length, newLength));
return newArray;
}
// always produces an Object[], whatever the input's element type was
public static Object[] naiveResize(Object[] a, int newLength) { // not useful
var newArray = new Object[newLength];
System.arraycopy(a, 0, newArray, 0, Math.min(a.length, newLength));
return newArray;
}
public static double cube(double x) {
return x * x * x;
}
// f must be a static method taking one double and returning a double
public static void tabulate(double from, double to, int n, Method f)
throws ReflectiveOperationException {
System.out.println(f); // the Method's toString is its full signature
double dx = (to - from) / (n - 1);
for (double x = from; x <= to; x += dx) {
double y = (Double) f.invoke(null, x); // null: static method has no implicit argument
System.out.printf(Locale.US, "%10.4f | %10.4f%n", x, y);
}
}
}
class Employee {
private final String name;
private double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public String getName() { return name; }
public double getSalary() { return salary; }
public void giveRaise(double pct) {
if (pct < -100) throw new IllegalArgumentException("pct < -100");
salary += salary * pct / 100;
}
}
[1, 2, 3, 0, 0, 0, 0, 0, 0, 0]
[red, green, blue, null, null] String[]
naiveResize: ClassCastException
[Ljava.lang.String; int
[[0, 0, 0], [0, 0, 42]]
Omar Haddad 57200.0
seven bright
wrapped: java.lang.IllegalArgumentException: pct < -100
wrong argument type: IllegalArgumentException
public static double Solution.cube(double)
0.0000 | 0.0000
0.5000 | 0.1250
1.0000 | 1.0000
1.5000 | 3.3750
2.0000 | 8.0000
public static double java.lang.Math.cbrt(double)
1.0000 | 1.0000
14.0000 | 2.4101
27.0000 | 3.0000
2.1544 2.1544
System.out.println(f) prints the full signature of the method as the table header. (Many Math methods, sqrt and abs for instance, are intrinsics: the JIT compiler replaces the call with a single CPU instruction.)
Why You Should Rarely Do This
Method.invoke works, but it gives up almost everything the compiler normally checks:
- If you invoke a method with the wrong arguments, you get an exception at runtime, not a compiler error.
- Parameters and return values are typed
Object, so you must cast back and forth, and the compiler can't check your code. - Reflective calls are slower than direct calls, and they need boxing for primitives.
Keep reflective calls for frameworks and tools that truly can't know the method at compile time. Elsewhere, a functional interface does the same job with full type checking:
static void tabulate(double from, double to, int n, DoubleUnaryOperator f) {
. . .
double y = f.applyAsDouble(x);
}
tabulate(1, 27, 3, Math::cbrt);
tabulate(1, 10, 10, x -> x * x);
When you really need dynamic invocation (frameworks, interpreters, scripting bridges), consider method handles from java.lang.invoke. A MethodHandle is looked up once with an exact type, can be invoked with invokeExact without boxing, and is well optimized by the JIT. Since Java 18, core reflection itself is implemented on top of method handles (JEP 416):
MethodHandle mh = MethodHandles.lookup().findStatic(Math.class, "cbrt",
MethodType.methodType(double.class, double.class));
double r = (double) mh.invokeExact(2.0);
Common questions
Why can't I write new T[n] in a generic method?
Because of type erasure, the runtime doesn't know what T is, and an array must know its element type. Pass the information in: a Class<T> (then Array.newInstance(cls, n)), an IntFunction<T[]> such as String[]::new, or an existing array whose component type you copy, as Arrays.copyOf does.
How do I call a static method reflectively?
Look it up with getMethod(name, paramTypes...) and call m.invoke(null, args...). The first argument is ignored for static methods, so null is conventional.
Why is the exception from my reflectively called method wrapped?
Method.invoke wraps anything that the target method throws in an InvocationTargetException. That way you can tell a failed reflective call (wrong arguments, no access) from a failure inside the called code. Call getCause() to get the original exception.
Are method handles faster than reflection?
A MethodHandle stored in a static final field can be optimised by the JIT almost like a direct call, and invokeExact avoids boxing. Since Java 18, Method.invoke itself uses method handles internally, so the gap is smaller than it used to be. Both are still slower than ordinary calls or lambdas.
What's the modern replacement for passing Method objects around?
Functional interfaces and method references: DoubleUnaryOperator f = Math::cbrt;. They're type-checked by the compiler, need no exception handling, and are fast. Reflection is only needed when the method's name is known only at runtime.
Summary
Array.newInstance(componentType, length)creates an array of a type known only at runtime. Combined withgetComponentTypeandArray.getLength, it lets you write aresizethat works for every array type, including primitive arrays.- An array created as
Object[]can never be cast toEmployee[]. Arrays remember their element type. Method.invoke(obj, args...)calls a method. Passnullasobjfor static methods. Primitive arguments and results are wrapped.- Find methods with
getMethod(name, parameterTypes...)and constructors withgetConstructor(parameterTypes...). Then callnewInstance(args...). - Exceptions thrown by the invoked code arrive wrapped in
InvocationTargetException. - Prefer interfaces, lambdas and method references. For dynamic invocation in frameworks, method handles are the modern tool.
Practice Questions
Why can't naiveResize's result be cast to String[], even though it only contains strings?
The array was created with new Object[n], so its runtime type is Object[]. Arrays keep their creation element type, and a cast can't change the runtime type of an object, so the cast throws ClassCastException.
Why does resize take a parameter of type Object instead of Object[]?
So that primitive arrays such as int[] can be passed. An int[] is an Object, but it isn't an Object[].
Write reflective code that calls the static method Integer.parseInt on the string "42" and prints the result plus one.
Method parse = Integer.class.getMethod("parseInt", String.class);
int value = (Integer) parse.invoke(null, "42");
System.out.println(value + 1); // 43
A reflectively invoked method throws IllegalStateException. Which exception does the caller of invoke catch, and how does it get the original?
It catches InvocationTargetException. e.getCause() returns the original IllegalStateException.
Why does getMethod need parameter types in addition to the method name?
Methods can be overloaded, so a name may refer to several methods. The parameter types select one, e.g. getMethod("println", String.class) versus getMethod("println", int.class).
Create a two-dimensional double array with 3 rows and 4 columns using reflection, and set element [2][3] to 1.5.
Object m = Array.newInstance(double.class, 3, 4);
Array.setDouble(Array.get(m, 2), 3, 1.5);
double[][] matrix = (double[][]) m;
Previous: Java Reflection: Analyzing Classes and Inspecting Objects at Runtime
Next: Java Inheritance Design Hints: Best Practices for Class Hierarchies
Related reading
- Java Reflection: Analyzing Classes and Inspecting Objects at Runtime
- Java Reflection: The Class Class, Exceptions Primer and Loading Resources
- Java ArrayList: Generic Array Lists Explained
- Processing Java Annotations at Runtime with Reflection
- Java Pattern Matching: switch Patterns, Record Patterns and Guards

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.