invoke
- Java course
- Advanced
- Lesson 28/82
- 5 min
Learn dynamic calls with Method.invoke.
Calling methods with Method.invoke
To call a Method object at runtime you use invoke. The first parameter is the target instance; the rest are the method's parameters.
Example: Object result = m.invoke(target, args). Here target is the instance on which the method is called and args is the array of parameters. For static methods target can be null. The return value comes back as an Object; you cast it when needed.
Calling private methods
To call a private method you first need setAccessible(true). This bypasses access checks; then invoke runs.
Example: m.setAccessible(true); m.invoke(target). This pattern is used in library and test code to reach hidden methods. The module system adds some restrictions, but in single-file applications setAccessible generally works. Use it carefully in production code; it can break encapsulation.
Practice Invoke the String.length method
Assign "Hello" to a String variable. Find the length method with String.class.getMethod("length"). Call it with m.invoke(s) and print the result with System.out.println. Add throws Exception to main.
Starter code
import java.lang.reflect.Method;
// Assign "Hello" to a String variable
// Find the length method with getMethod
// Invoke it and print the resultSample solution
import java.lang.reflect.Method;
public class InvokeLength {
public static void main(String[] args) throws Exception {
String s = "Hello";
Method m = String.class.getMethod("length");
System.out.println(m.invoke(s));
}
}Expected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the invoke call
Object result = method.____(target, args);
Object result = method.invoke(target, args);
Explanation: answer: invoke. It takes the target and parameters.
2 Match the invoke concepts
| Term | Meaning |
|---|---|
invoke |
Call the method |
setAccessible |
Open access |
getMethod |
Find a method |
IllegalAccessException |
Access blocked |
3 Which exception is thrown when invoking an inaccessible method?
- NullPointerException
- ClassCastException
- IOException
- IllegalAccessException Correct answer
Explanation: IllegalAccessException is thrown when access is blocked.