Course contentsShow
← Java
Lesson 2343 of 2,87045. Reflection APIFree lesson

Basic invoke Syntax: Target Object and Arguments

Learning the signature of Method.invoke(Object obj, Object... args) and how to pass the target instance.

Basic invoke Syntax: Target Object and Arguments

You'll learn how to actually call a method using reflection by passing the right target object and arguments to Method.invoke().

Now that you've obtained a Method object from a class, it's time to execute it. The invoke() method is your gateway to calling any method reflectively, and understanding its signature is essential.

The invoke() Signature

public Object invoke(Object obj, Object... args)

This method takes two key pieces of information:

  1. obj — The target instance on which the method should be called (the "receiver")
  2. args — A variable-length argument list containing the actual arguments to pass to the method

Understanding the Target Object

Think of obj as the "who" — whose method are you calling? For instance methods, this must be an actual instance of the class. For static methods, you pass null because static methods don't need an instance.

Class<?> clazz = String.class;
Method method = clazz.getMethod("toUpperCase");

String target = "hello";
Object result = method.invoke(target); // "HELLO"

Here, target is the specific String object whose toUpperCase() method we're calling.

Passing Arguments

The args parameter is a varargs array, so you simply list the arguments in order:

Method substring = String.class.getMethod("substring", int.class, int.class);
String text = "Java Reflection";
Object result = substring.invoke(text, 5, 14); // "Reflection"

The arguments 5 and 14 are passed as the begin and end indices.

Key Takeaway: Method.invoke(obj, args) requires the target instance as the first parameter (or null for static methods) and the method arguments as subsequent parameters—this is how you execute any method reflectively in Java.