Reflection
Inspecting Methods
Query methods, inspect signatures, and invoke methods dynamically using reflection.
Interview: Focuses on Method.invoke() execution, type mapping parameters, and handling InvocationTargetException.
The Reflection API allows dynamically locating methods by name and parameter types, and invoking them on object instances.
Core Idea
Methods can be looked up dynamically and executed using Method.invoke(instance, args).
Why It Matters
Allows RPC (Remote Procedure Call) and routing frameworks to map incoming HTTP endpoints to methods dynamically.
Interview Lens
Focuses on exception wrapper handling, specifically handling InvocationTargetException.
Method Invocation
To invoke a method:
1. Find the Method object using getDeclaredMethod(name, parameterTypes...).
2. Execute the method using method.invoke(targetInstance, arguments...).
3. If the method is static, pass null as the targetInstance.
Code Walkthrough
This program shows how to invoke a private method with parameters dynamically.
import java.lang.reflect.Method;class Calculator { private int add(int a, int b) { return a + b; } }
public class MethodReflectionDemo { public static void main(String[] args) throws Exception { Calculator calc = new Calculator();
// Get method by name and parameter types Method method = Calculator.class.getDeclaredMethod("add", int.class, int.class);
method.setAccessible(true);
// Invoke on instance with arguments Integer result = (Integer) method.invoke(calc, 10, 15); System.out.println("Result of add method: " + result); // 25 } }
Interview-Relevant Information
Q: How do you capture exceptions thrown inside an invoked method?
Answer: If the method executed via invoke() throws an exception, the reflection framework catches it and wraps it inside a checked InvocationTargetException. You must catch this exception and call e.getCause() to access the original application error.
Quick Checklist
How do you invoke a static method? What exception wraps errors thrown inside the method? If yes, you understand method reflection.
Use Cases
Dynamic routing maps inside controllers.
Plugin execution systems loading external jar methods.
Common Mistakes
Forgetting to supply the method parameter types in getDeclaredMethod(), throwing NoSuchMethodException.
Not catching InvocationTargetException, failing to log the root application stacktrace.