Processing Java Annotations at Runtime with Reflection
Read Java annotations at runtime with the AnnotatedElement API: getAnnotation, getAnnotationsByType, declared versus inherited annotations, and three hands-on tools built with reflection, an annotation-driven toString, a mini JUnit-style test runner and a record validator.
kvi5hnuCode Sprout team member8 min readOn this page
Annotations become useful when a tool acts on them. The simplest such tool is your own code, reading annotations at runtime through reflection. JUnit, Jakarta Bean Validation, Jackson and Spring all work this way. This article explains the reflection methods for annotations, then builds three small tools: a customizable toString, a test runner, and a validator.
The AnnotatedElement interface
The reflection classes that can carry annotations, namely Class, Field, Method, Constructor, Parameter, RecordComponent, Package and Module, implement java.lang.reflect.AnnotatedElement:
<T extends Annotation> T getAnnotation(Class<T> annotationType)
<T extends Annotation> T getDeclaredAnnotation(Class<T> annotationType)
<T extends Annotation> T[] getAnnotationsByType(Class<T> annotationType)
<T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationType)
Annotation[] getAnnotations()
Annotation[] getDeclaredAnnotations()
boolean isAnnotationPresent(Class<? extends Annotation> annotationType)
As with other reflection methods, the Declared versions return only annotations present on the item itself, and the others also include inherited ones. For annotations, that only matters for @Inherited annotations on a superclass (article 107).
Only annotations with RUNTIME retention are visible here. If something seems to be missing, check its @Retention first.
Reading a single annotation
For an annotation that isn't repeatable, call getAnnotation with the annotation's class object:
Class<?> cl = obj.getClass();
Describe desc = cl.getAnnotation(Describe.class);
if (desc != null && desc.withName()) ...
You get back an object of a proxy class that implements Describe, and you call its methods to read the element values. If the annotation isn't present, the result is null.
Repeatable annotations
With a repeatable annotation, getAnnotation is a trap. If the annotation was used more than once, the compiler wrapped the repeats into the container annotation, so getAnnotation returns null. Call getAnnotationsByType instead. It looks through the container and returns an array of all the repeated annotations, of length 1 if there was just one and of length 0 if there were none. You never have to deal with the container.
getAnnotations returns all annotations of any type, with repeats still wrapped in their containers. All the array-returning methods return an empty array, never null, when nothing is present.
Parameters have one more method on Method and Constructor: getParameterAnnotations() returns an Annotation[][] with one row per parameter. You can also iterate getParameters() and query each Parameter directly.
Tool 1: an annotation-driven toString
Hand-written toString methods are repetitive, and a fully generic reflective one dumps every field whether you want it or not. An annotation lets each class opt in and choose what appears: which fields are shown, and whether the class and field names are printed. With names switched off, a Pixel shows up as just {3, 7}.
The annotation marks both the classes that take part and the fields to include:
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.RECORD_COMPONENT})
@Retention(RetentionPolicy.RUNTIME)
public @interface Describe {
boolean withName() default true;
}
Annotated classes look like this:
@Describe(withName = false)
public class Pixel {
@Describe(withName = false) private int x;
@Describe(withName = false) private int y;
...
}
@Describe
public record Tile(@Describe(withName = false) Pixel corner,
@Describe int width,
@Describe int height) { }
For new Tile(new Pixel(3, 7), 16, 9) we want Tile{{3, 7}, width=16, height=9}. Reflection can't swap out a class's own toString, so the tool is a static helper, describe, that accepts any object and consults its @Describe annotations if it has them:
public static String describe(Object obj) {
if (obj == null) return "null";
Class<?> type = obj.getClass();
Describe onClass = type.getAnnotation(Describe.class);
if (onClass == null) return String.valueOf(obj); // unannotated: fall back to its own toString
String prefix = onClass.withName() ? type.getSimpleName() + "{" : "{";
var parts = new StringJoiner(", ", prefix, "}");
for (Field field : type.getDeclaredFields()) {
Describe onField = field.getAnnotation(Describe.class);
if (onField == null) continue; // not marked: leave it out
String label = onField.withName() ? field.getName() + "=" : "";
try {
field.setAccessible(true);
parts.add(label + describe(field.get(obj))); // nested values go through describe too
} catch (ReflectiveOperationException e) {
parts.add(label + "<unreadable>");
}
}
return parts.toString();
}

Each field value is passed back into describe, so a Pixel inside a Tile is formatted by the same rules. The recursion bottoms out at values whose class carries no @Describe (numbers, strings, collections), which fall back to their normal toString. The @Describe on the record components is passed on to the generated private fields (FIELD is a target), so getDeclaredFields finds it there.
This is the typical pattern for runtime annotation processing:
- Find the classes, fields, methods and so on through reflection.
- Call
getAnnotationorgetAnnotationsByTypeon them. - Call the annotation interface's methods to read the element values, then act on them.
Tool 2: a tiny test runner
JUnit started as little more than this loop: find the methods annotated with @Test, create a fresh instance of the test class, run any @BeforeEach method, invoke the test, and record the outcome. The demo's runner also supports an expected exception element and repeatable @Tags:
@Test(expected = ArithmeticException.class)
public void dividesByZero() { ... }
Two reflection details matter here:
Method.invokewraps any exception thrown by the test in anInvocationTargetException. Unwrap it withgetCause()to see what the test actually threw.- Annotation elements can't be
null, so "no exception expected" is represented by a sentinel class (Test.None). JUnit 4 used exactly that trick.
Tool 3: declarative validation
Jakarta Bean Validation (@NotNull, @Size, @Min, …) and Spring's @Valid read constraint annotations at runtime. The demo's miniature version walks a record's components in order, reads each value through the accessor, and checks @NotBlank and @Range(min, max):
record User(@NotBlank String name, @Range(min = 0, max = 150) int age, String nickname) { }
It also prints the annotations on method parameters with getParameterAnnotations. A framework would use them to validate method arguments.
A complete example
import java.lang.annotation.*;
import java.lang.reflect.*;
import java.util.*;
public class Solution {
// ===== 1. an annotation-driven toString =====
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.RECORD_COMPONENT})
@Retention(RetentionPolicy.RUNTIME)
@interface Describe { boolean withName() default true; }
@Describe(withName = false)
static class Pixel {
@Describe(withName = false) private final int x;
@Describe(withName = false) private final int y;
private final String cachedLabel = "not shown"; // not annotated: skipped
Pixel(int x, int y) { this.x = x; this.y = y; }
}
@Describe
record Tile(@Describe(withName = false) Pixel corner,
@Describe int width,
@Describe int height) {}
static final class Descriptions {
static String describe(Object obj) {
if (obj == null) return "null";
Class<?> type = obj.getClass();
Describe onClass = type.getAnnotation(Describe.class);
if (onClass == null) return String.valueOf(obj); // unannotated: fall back to its own toString
String prefix = onClass.withName() ? type.getSimpleName() + "{" : "{";
var parts = new StringJoiner(", ", prefix, "}");
for (Field field : type.getDeclaredFields()) {
Describe onField = field.getAnnotation(Describe.class);
if (onField == null) continue; // not marked: leave it out
String label = onField.withName() ? field.getName() + "=" : "";
try {
field.setAccessible(true);
parts.add(label + describe(field.get(obj))); // nested values go through describe too
} catch (ReflectiveOperationException e) {
parts.add(label + "<unreadable>");
}
}
return parts.toString();
}
}
// ===== 2. a tiny test runner =====
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
@interface Test {
Class<? extends Throwable> expected() default None.class; // "no exception expected"
final class None extends Throwable { private static final long serialVersionUID = 1L; }
}
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface BeforeEach {}
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Repeatable(Tags.class) @interface Tag { String value(); }
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface Tags { Tag[] value(); }
public static class CalculatorTest {
private List<Integer> data;
@BeforeEach public void setUp() { data = new ArrayList<>(List.of(3, 1, 2)); }
@Test @Tag("fast") public void sorts() { Collections.sort(data); check(data.equals(List.of(1, 2, 3))); }
@Test @Tag("fast") @Tag("math") public void sums() { check(data.stream().mapToInt(i -> i).sum() == 7); } // deliberately wrong: 3 + 1 + 2 is 6
@Test(expected = ArithmeticException.class) public void dividesByZero() { System.out.print(1 / (data.size() - 3)); }
@Test(expected = ArithmeticException.class) public void forgetsToThrow() { }
public void helper() { throw new AssertionError("not a test, never run"); }
static void check(boolean ok) { if (!ok) throw new AssertionError("check failed"); }
}
static void runTests(Class<?> cl) throws ReflectiveOperationException {
Method[] methods = cl.getDeclaredMethods();
Arrays.sort(methods, Comparator.comparing(Method::getName)); // getDeclaredMethods has no fixed order
Method before = Arrays.stream(methods).filter(m -> m.isAnnotationPresent(BeforeEach.class)).findFirst().orElse(null);
int passed = 0, failed = 0;
for (Method m : methods) {
Test t = m.getAnnotation(Test.class);
if (t == null) continue;
var tags = Arrays.stream(m.getAnnotationsByType(Tag.class)).map(Tag::value).toList();
Object instance = cl.getDeclaredConstructor().newInstance(); // fresh instance per test
if (before != null) before.invoke(instance);
String outcome;
try {
m.invoke(instance);
outcome = t.expected() == Test.None.class ? "PASS" : "FAIL (expected " + t.expected().getSimpleName() + ")";
} catch (InvocationTargetException e) { // the test threw
Throwable cause = e.getCause();
outcome = t.expected().isInstance(cause) ? "PASS (threw " + cause.getClass().getSimpleName() + ")"
: "FAIL (" + cause + ")";
}
if (outcome.startsWith("PASS")) passed++; else failed++;
System.out.println(" " + m.getName() + " " + tags + ": " + outcome);
}
System.out.println(" " + passed + " passed, " + failed + " failed");
}
// ===== 3. declarative validation on record components and parameters =====
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.RECORD_COMPONENT, ElementType.PARAMETER}) @interface NotBlank {}
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.RECORD_COMPONENT, ElementType.PARAMETER})
@interface Range { int min() default Integer.MIN_VALUE; int max() default Integer.MAX_VALUE; }
record User(@NotBlank String name, @Range(min = 0, max = 150) int age, String nickname) {}
static List<String> validate(Record r) throws ReflectiveOperationException {
var errors = new ArrayList<String>();
for (RecordComponent c : r.getClass().getRecordComponents()) {
Object value = c.getAccessor().invoke(r);
if (c.isAnnotationPresent(NotBlank.class) && (value == null || value.toString().isBlank()))
errors.add(c.getName() + " must not be blank");
Range range = c.getAnnotation(Range.class);
if (range != null && value instanceof Integer n && (n < range.min() || n > range.max()))
errors.add(c.getName() + " must be in [" + range.min() + ", " + range.max() + "] but was " + n);
}
return errors;
}
static void greet(@NotBlank String name, @Range(min = 1, max = 3) int times) {}
public static void main(String[] args) throws Exception {
System.out.println("-- annotation-driven toString --");
var tile = new Tile(new Pixel(3, 7), 16, 9);
System.out.println(" " + Descriptions.describe(tile));
System.out.println(" " + Descriptions.describe(new Pixel(-2, 4)));
System.out.println(" unannotated object: " + Descriptions.describe(List.of(1, 2)));
System.out.println("-- a tiny test runner --");
runTests(CalculatorTest.class);
System.out.println("-- validation --");
System.out.println(" valid user: " + validate(new User("Ada", 36, null)));
System.out.println(" invalid user: " + validate(new User(" ", 200, "x")));
Method greet = Solution.class.getDeclaredMethod("greet", String.class, int.class);
Annotation[][] pa = greet.getParameterAnnotations();
for (int i = 0; i < pa.length; i++)
System.out.println(" parameter " + i + " annotations: "
+ Arrays.stream(pa[i]).map(a -> a.annotationType().getSimpleName()).toList());
System.out.println("-- getAnnotations vs getAnnotationsByType --");
Method sums = CalculatorTest.class.getDeclaredMethod("sums");
System.out.println(" getAnnotations: " + Arrays.stream(sums.getAnnotations()).map(a -> a.annotationType().getSimpleName()).sorted().toList());
System.out.println(" getAnnotationsByType(Tag): " + Arrays.stream(sums.getAnnotationsByType(Tag.class)).map(Tag::value).toList());
System.out.println(" no annotations -> empty array: " + CalculatorTest.class.getDeclaredMethod("helper").getAnnotations().length);
}
}
-- annotation-driven toString --
Tile{{3, 7}, width=16, height=9}
{-2, 4}
unannotated object: [1, 2]
-- a tiny test runner --
dividesByZero []: PASS (threw ArithmeticException)
forgetsToThrow []: FAIL (expected ArithmeticException)
sorts [fast]: PASS
sums [fast, math]: FAIL (java.lang.AssertionError: check failed)
2 passed, 2 failed
-- validation --
valid user: []
invalid user: [name must not be blank, age must be in [0, 150] but was 200]
parameter 0 annotations: [NotBlank]
parameter 1 annotations: [Range]
-- getAnnotations vs getAnnotationsByType --
getAnnotations: [Tags, Test]
getAnnotationsByType(Tag): [fast, math]
no annotations -> empty array: 0
Common questions
What is the difference between getAnnotation and getDeclaredAnnotation?
getAnnotation also finds @Inherited annotations from superclasses. getDeclaredAnnotation only looks at annotations written directly on the element. For methods and fields, which never inherit annotations, they behave the same.
Is reflection-based annotation processing slow?
Reading annotations and calling methods reflectively is slower than direct code, but the cost is usually small next to the real work. Frameworks scan each class once, cache what they find, and often use MethodHandles for the actual calls.
Why does Method.invoke throw InvocationTargetException instead of my exception?
invoke wraps any exception thrown by the called method. Call getCause() to get the original exception, as test runners do.
Does getDeclaredFields return fields in declaration order?
In practice HotSpot usually does, but the specification doesn't promise it. If order matters, sort the members, or use records, whose getRecordComponents() is guaranteed to be in declaration order.
Why does my framework fail with InaccessibleObjectException?
setAccessible(true) is refused for packages in named modules that aren't opened to the framework. Add an opens directive to module-info.java, or --add-opens on the command line for code you don't control.
API reference
java.lang.reflect.AnnotatedElement
| Method | Description |
|---|---|
boolean isAnnotationPresent(Class<? extends Annotation> type) | true if this item has an annotation of the given type |
<T extends Annotation> T getAnnotation(Class<T> type) | the annotation of the given type, including inherited ones, or null |
<T extends Annotation> T getDeclaredAnnotation(Class<T> type) | as above, ignoring inherited annotations (Java 8) |
<T extends Annotation> T[] getAnnotationsByType(Class<T> type) | all annotations of a (repeatable) type, looking into containers; empty array if none (Java 8) |
<T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> type) | as above, ignoring inherited annotations (Java 8) |
Annotation[] getAnnotations() | all annotations present, including inherited ones; repeats stay in containers |
Annotation[] getDeclaredAnnotations() | all annotations declared on this item |
Related
| Method | Description |
|---|---|
Annotation[][] Method.getParameterAnnotations() (also Constructor) | annotations for each parameter |
RecordComponent[] Class.getRecordComponents() | record components in declaration order, with getAccessor() |
Object Method.invoke(Object obj, Object... args) | throws InvocationTargetException wrapping the method's exception |
Summary
Class,Field,Method,Constructor,Parameter,RecordComponent,PackageandModuleimplementAnnotatedElement. OnlyRUNTIMEannotations are visible.- Use
getAnnotationfor ordinary annotations (nullif absent) andgetAnnotationsByTypefor repeatable ones, since it looks through the container.Declaredvariants ignore@Inheritedannotations from superclasses. - The pattern is to discover elements by reflection, query their annotations, read the element values and act on them. Recursion,
setAccessible,invokeand record components are typical helpers. - Real frameworks also sort or order members, cache per class, unwrap
InvocationTargetExceptionand respect module encapsulation.
Practice Questions
What does getAnnotation return if the annotation isn't present, and what do getAnnotations and getAnnotationsByType return?
getAnnotation returns null. The array-returning methods return an empty array, never null.
Why might the Descriptions.describe method of this article print fields in a surprising order on some JVM?
Class.getDeclaredFields() doesn't specify any order. Most JVMs return declaration order, but a robust tool should sort the fields, use an explicit order element, or use getRecordComponents(), which is ordered.
A test method throws IllegalStateException when invoked through Method.invoke. What does the runner catch?
An InvocationTargetException, whose getCause() is the IllegalStateException. Reflection wraps exceptions thrown by the invoked method so they can be told apart from reflection problems such as IllegalAccessException.
How does the recursion in the annotation-driven toString terminate?
For each field value it calls itself. When it reaches an object whose class has no @Describe annotation, such as an Integer or String, it returns the value's own toString() without recursing further. null also stops the recursion.
A method has @Tag("a") @Tag("b"). What do getAnnotations() and getAnnotationsByType(Tag.class) return?
getAnnotations() returns the container @Tags({@Tag("a"), @Tag("b")}) together with the other annotations, but no @Tag directly. getAnnotationsByType(Tag.class) returns the two @Tag annotations.
Previous: Java Built-in Annotations: @Override, @Deprecated, @SuppressWarnings and Meta-Annotations
Next: Java Annotation Processors: Generating Source Code at Compile Time
Related reading
- Java Built-in Annotations: @Override, @Deprecated, @SuppressWarnings and Meta-Annotations
- Defining Custom Java Annotations: @interface, Elements, Retention and Target
- Java Annotations Explained: Syntax, Uses and Where You Can Annotate
- Java Processes and ProcessBuilder: Running and Managing External Programs
- Java Long-Running Tasks in User Interfaces: Swing Worker Threads and Callbacks

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.