Sub topic 2
Invoking Methods and Unwrapping `InvocationTargetException`
Assume you know Java classes, methods, constructors, annotations, checked exceptions, and basic reflection. Reflection lets a program find and use members whose names are known only at runtime.
Invoking Methods
Use getMethod for a public method, then call Method.invoke. The call returns an Object, and method arguments follow the method object.
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectionChapterDemo {
private String name = "Ada";
public String greet(String person) {
return "Hello " + person + ", I am " + name;
}
public void fail() {
throw new IllegalStateException("operation failed");
}
public static void main(String[] args) throws Exception {
ReflectionChapterDemo target = new ReflectionChapterDemo();
Field field = ReflectionChapterDemo.class.getDeclaredField("name");
field.setAccessible(true);
field.set(target, "Grace");
Method greet = ReflectionChapterDemo.class
.getMethod("greet", String.class);
System.out.println(greet.invoke(target, "Linus"));
Method fail = ReflectionChapterDemo.class.getMethod("fail");
try {
fail.invoke(target);
} catch (InvocationTargetException e) {
System.out.println("Real cause: " + e.getCause());
}
}
}InvocationTargetException means the invoked method threw an exception. The original exception is its cause. Inspect getCause() instead of treating the wrapper as the application error.
Private Members and Java Modules
getDeclaredField and getDeclaredMethod can find non-public members. Calling setAccessible(true) requests permission to bypass Java language access checks. It may throw InaccessibleObjectException when the Java module system does not open the containing package.
Use trySetAccessible() when failure should be handled as a result. A package being exported does not automatically mean its private members are open to reflection. Prefer public APIs or explicit module configuration over bypassing encapsulation.
Declaring and Applying Annotations
An annotation is metadata attached to program elements. Runtime code can read it only when its retention policy is RUNTIME.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
@Repeatable(Labels.class)
@interface Label {
String value();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Labels {
Label[] value();
}
@Label("api")
@Label("stable")
class Service {}Meta-Annotations
Meta-annotations describe how an annotation behaves.
| Meta-annotation | Purpose |
|---|---|
| `@Retention` | Selects source, class-file, or runtime lifetime |
| `@Target` | Restricts where the annotation may appear |
| `@Inherited` | Lets subclasses inherit a class annotation |
| `@Repeatable` | Allows multiple uses with the same target |
Read repeated annotations with getAnnotationsByType(Label.class), which handles both direct and container forms.
Exercise
Why should code catch InvocationTargetException and inspect getCause()?
Show answer
Because the wrapper reports reflective invocation failure, while getCause() contains the exception actually thrown by the target method.