Sub topic 3
Reading Annotations at Runtime
Assume you know Java classes, reflection basics, generics, and checked exceptions. This chapter focuses on using metadata to drive program behavior.
Reading runtime annotations
An annotation is metadata attached to a declaration. Reflection can read it only when its retention is RUNTIME.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface NotBlank {
String message() default "must not be blank";
}For a field, call getAnnotation:
NotBlank rule = field.getAnnotation(NotBlank.class);The result is null when the annotation is absent. @Target limits where the annotation can be used. Other useful meta-annotations include @Inherited and @Repeatable.
An annotation-driven validator
The validator below finds annotated fields and checks their values.
import java.lang.annotation.*;
import java.lang.reflect.Field;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface NotBlank {
String message() default "must not be blank";
}
class User {
@NotBlank
private String name;
@NotBlank(message = "email is required")
private String email;
User(String name, String email) {
this.name = name;
this.email = email;
}
}
public class ValidatorDemo {
static void validate(Object object) throws IllegalAccessException {
for (Field field : object.getClass().getDeclaredFields()) {
NotBlank rule = field.getAnnotation(NotBlank.class);
if (rule == null) continue;
field.setAccessible(true);
Object value = field.get(object);
if (value == null || value.toString().trim().isEmpty()) {
System.out.println(field.getName() + ": " + rule.message());
}
}
}
public static void main(String[] args) throws Exception {
validate(new User("Ada", ""));
}
}Generic type information and erasure
Java erases most generic type arguments from runtime objects. However, declarations retain generic signatures in the class file. field.getGenericType() can therefore reveal that a field is declared as List<String>, even though a list object does not remember String at runtime. Cast the result to ParameterizedType to inspect its arguments.
Dynamic proxies
Proxy.newProxyInstance creates an object implementing one or more interfaces. Each call goes to an InvocationHandler. This supports logging, authorization, transactions, and similar cross-cutting behavior. Proxies cannot directly implement ordinary classes.
Method handles compared with `Method.invoke`
Method.invoke is simple and works with reflective Method objects. It performs access and argument checks and wraps target exceptions in InvocationTargetException. A MethodHandle has a precise MethodType and can be faster after repeated use, but invokeExact requires exact compile-time types.
Performance, safety, and processing
Reflection adds lookup, access checks, boxing, and weaker compile-time guarantees. Cache reusable Field and Method objects, validate inputs, and avoid exposing private state unnecessarily. setAccessible(true) may be rejected by Java's module system when a package is not open.
Compile-time annotation processing examines annotations while compiling. It can generate source code or report errors before execution. Prefer it when generated code and compile-time safety are more valuable than runtime flexibility.
Exercise
Why must NotBlank use RUNTIME retention for the validator to find it?
Show answer
Reflection reads annotations during execution, so the annotation must remain available in the compiled class at runtime.