Java Annotations Explained: Syntax, Uses and Where You Can Annotate
Learn how Java annotations work: what they are for, element syntax and defaults, value and single-element shortcuts, repeated annotations, annotating declarations, packages and record components, type-use annotations on generics and arrays, and receiver parameters.
kvi5hnuCode Sprout team member10 min readOn this page
If you've used JUnit, Spring, Jakarta Persistence or Lombok, you've written annotations such as @Test, @Autowired, @Entity and @Override. Annotations are tags you put into source code so that some tool can process them. That tool might be the compiler, a static checker, a code generator, or a framework reading them through reflection at runtime. This article covers the syntax for using annotations: elements, shortcuts, repetition, and all the places where annotations can appear. The next articles show how to define and process your own.
What annotations do (and don't do)
Annotations don't change how your program is compiled. The compiler generates the same bytecode instructions with or without them. By itself, an annotation does nothing. To benefit from one, you need a processing tool that understands it:
- JUnit finds the methods marked
@Testand calls them, and other annotations control how the tests run. - Jakarta Persistence (JPA) maps classes annotated with
@Entityto database tables, so objects are persisted without hand-written SQL. - Command-line parsers such as picocli and JCommander turn annotated fields into command-line options.
- The compiler itself checks
@Overrideand@FunctionalInterfaceand honors@SuppressWarningsand@Deprecated(article 107). - Static analyzers such as the Checker Framework, NullAway and IntelliJ's inspections verify
@NonNulland@Nullablecontracts. - Annotation processors generate code at compile time. Lombok, MapStruct, Dagger and Immutables work this way (article 109).
Tools work either at the source level or on class files and loaded classes, where the compiler has placed the annotations.
Using an annotation
An annotation is used like a modifier such as public or static. Its name is preceded by @:
class CacheTest {
@Test void checkRandomInsertions() { ... }
}
@Test annotates the checkRandomInsertions method. On its own it's just a marker. When JUnit runs, it looks for methods annotated with @Test and calls them.
Annotation elements
Annotations can carry key/value pairs called elements:
@RepeatedTest(value = 10, failureThreshold = 3)
Each annotation defines which elements it has and their types (article 106). An element value must be one of these:
- a primitive type value
- a
String - a
Classobject, such asCacheTest.class - an enum constant
- another annotation
- an array of any of the above, but not an array of arrays
Here's a made-up @BugReport annotation that uses all of them:
@BugReport(showStopper = true,
assignedTo = "Omar",
testCase = CacheTest.class,
status = BugReport.Status.CONFIRMED,
ref = @Reference(id = 11235811),
reportedBy = {"Omar", "Fred"})
Two important restrictions apply:
- Values must be compile-time constants, because the compiler processes annotations. You can't write
assignedTo = user.getName(), but astatic final Stringconstant works. - An element can never be
null. Not as a value, and not as a default. Tools use sentinels such as""orVoid.classfor "not set".
There are three shortcuts:
- Single-element arrays don't need braces.
@BugReport(reportedBy = "Omar")is the same asreportedBy = {"Omar"}. - Defaults. Elements can have default values. JUnit's
failureThresholddefaults toInteger.MAX_VALUE, so@RepeatedTest(value = 10)means@RepeatedTest(value = 10, failureThreshold = Integer.MAX_VALUE), and the test is repeated ten times however often it fails. value. If an element is namedvalueand it's the only one you specify, you can leave outvalue =.@RepeatedTest(10)is@RepeatedTest(value = 10), and@SuppressWarnings("unchecked")works the same way.
An annotation with no elements, or with all elements defaulted, can be written without parentheses: @Test, @Override. Such annotations are called marker annotations.
Multiple and repeated annotations
An item can carry any number of different annotations:
@Test
@Tag("localized")
void testHello() { ... }
If the annotation's author declared it repeatable, you can use the same annotation several times:
@Tag("localized")
@Tag("showstopper")
void testHello() { ... }
Behind the scenes, the compiler packs repeated annotations into a container annotation, here @Tags({...}). Article 106 explains why that matters to tools.
Annotating declarations
Annotations appear in two kinds of places: declarations and type uses. Declaration annotations can be attached to the declarations of
- classes (including
enums and records) and interfaces (including annotation interfaces) - methods and constructors
- fields (including enum constants and record components)
- local variables (including those in
forand try-with-resources statements) - parameters and
catchclause parameters - type parameters
- packages and modules
For classes, interfaces and modules, put annotations before the class, interface or module keyword and any modifiers:
@Entity public class User { ... }
For variables, put them before the type:
@SuppressWarnings("unchecked") List<User> users = ...;
public User getUser(@Param("id") String userId)
Record components and type parameters work the same way:
public record Tile(@Label("width in px") int width, int height) { ... }
public class Cache<@NonNull V> { ... }
An annotation on a record component is propagated to the generated field, accessor method and canonical-constructor parameter, wherever the annotation is allowed. The demo shows @Label arriving on both the field and the accessor.
Packages are annotated in a special file, package-info.java, which contains only documentation, the annotations and the package statement. Note that the annotation's import comes after the package line:
/**
* Package-level documentation
*/
@Generated("com.example.generator")
package com.example.generated;
import javax.annotation.processing.Generated;
Annotating type uses
A declaration annotation describes the declared item. In
public User getUser(@NonNull String userId)
it asserts that the parameter userId is never null. Now suppose the parameter is a List<String> and you want to say that the strings in the list are non-null. That's a property of a type use, and you write the annotation right before the type argument:
List<@NonNull String>

Type-use annotations (Java 8) can appear in the following places:
- Generic type arguments:
List<@NonNull String>,Comparator.<@NonNull String>reverseOrder(). - Any position of an array type:
@NonNull String[][] wordsmeanswords[i][j]isn't null.String @NonNull [][] wordsmeanswordsitself isn't null.String[] @NonNull [] wordsmeans eachwords[i]isn't null.
- Superclasses and implemented interfaces:
class Warning extends @Localized Message. - Constructor invocations:
new @Localized String(...). - Nested types:
Map.@Localized Entry. - Casts and
instanceof:(@Localized String) text,if (text instanceof @Localized String). These are for external tools only, so the cast or test behaves exactly the same. - Exception specifications:
public String read() throws @Localized IOException. - Wildcards and bounds:
List<@Localized ? extends Message>,List<? extends @Localized Message>. - Method and constructor references:
@Localized Message::getText.
A few positions can't be annotated:
@NonNull String.class // ERROR: cannot annotate a class literal
import java.lang.@NonNull String; // ERROR: cannot annotate an import
The @NonNull and @Localized examples come from the Checker Framework. You write such assertions in your code, and a static analysis tool checks them against the whole code base. JSpecify (org.jspecify.annotations.Nullable/NonNull, version 1.0 in 2024) is an emerging common standard for nullness annotations, supported by NullAway, IntelliJ, Kotlin and Spring.
Placement convention. Annotations can go before or after modifiers such as private and static. By custom, type-use annotations come after the modifiers and declaration annotations before them:
private @NonNull String text; // annotates the type use
@Id private String userId; // annotates the variable
If an annotation is allowed both on a declaration and on a type use, and you use it in a declaration, both are annotated. With such a @NonNull, getUser(@NonNull String userId) annotates the parameter and makes the parameter's type @NonNull String.
Making receivers explicit
Suppose a tool checks which parameters a method doesn't mutate, and you annotate:
public class Point {
public boolean equals(@ReadOnly Object other) { ... }
}
A tool seeing p.equals(q) concludes that q isn't changed. But what about p? Inside the method it's this, which is never declared, so there's nowhere to put an annotation. For this purpose Java has a rarely used syntax. You can declare this as an explicit first parameter, called the receiver parameter:
public boolean equals(@ReadOnly Point this, @ReadOnly Object other) { ... }
It must be named this, and its type is the enclosing class. It isn't a real parameter, so callers still write p.equals(q) and reflection reports one parameter. A receiver parameter is allowed for methods, but not for constructors, because during construction this isn't yet a fully formed object of that type. An annotation on the constructor itself describes the constructed object instead.
An inner class constructor has a different hidden parameter, the reference to the outer object. You can make it explicit as well, named the way you refer to it, Outer.this:
static class Sequence {
private int from, to;
class Iterator implements java.util.Iterator<Integer> {
private int current;
public Iterator(@ReadOnly Sequence Sequence.this) {
this.current = Sequence.this.from;
}
...
}
}
A complete example
The demo declares a handful of runtime-visible annotations and uses them every way this article describes. It then plays the role of a "tool", using reflection to find annotated methods, read element values and defaults, collect repeated @Tags from their container, check propagation from a record component, and inspect type-use annotations on a generic type argument, three array positions, a superclass, an interface and a receiver parameter. Article 108 explains the reflection API in detail.
import java.lang.annotation.*;
import java.lang.reflect.*;
import java.util.*;
public class Solution {
// ---- annotation declarations (article 106 explains this syntax) ----
@Retention(RetentionPolicy.RUNTIME) @interface Test {}
@Retention(RetentionPolicy.RUNTIME) @interface RepeatedTest { int value(); int failureThreshold() default Integer.MAX_VALUE; }
@Retention(RetentionPolicy.RUNTIME) @Repeatable(Tags.class) @interface Tag { String value(); }
@Retention(RetentionPolicy.RUNTIME) @interface Tags { Tag[] value(); }
@Retention(RetentionPolicy.RUNTIME) @interface Reference { int id(); }
@Retention(RetentionPolicy.RUNTIME) @interface BugReport {
enum Status { UNCONFIRMED, CONFIRMED, FIXED }
boolean showStopper() default false;
String assignedTo() default "[none]";
Class<?> testCase() default Void.class;
Status status() default Status.UNCONFIRMED;
Reference ref() default @Reference(id = 0);
String[] reportedBy() default {};
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE, ElementType.PARAMETER, ElementType.TYPE_PARAMETER})
@interface NonNull {}
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE_USE) @interface Localized {}
@Retention(RetentionPolicy.RUNTIME) @interface Label { String value(); }
// ---- using annotations ----
static class CacheTest {
@Test void checkRandomInsertions() {}
@RepeatedTest(10) void retriesDefault() {}
@RepeatedTest(value = 10, failureThreshold = 3) void retriesThree() {}
@Test
@Tag("localized")
@Tag("showstopper")
void testHello() {}
@BugReport(showStopper = true,
assignedTo = "Omar",
testCase = CacheTest.class,
status = BugReport.Status.CONFIRMED,
ref = @Reference(id = 11235811),
reportedBy = {"Omar", "Fred"})
void buggy() {}
@BugReport(reportedBy = "Omar") // single-element array: braces optional
void minorBug() {}
}
record Tile(@Label("width in px") int width, int height) {}
static class Cache<@NonNull V> {
private final Map<String, V> map = new HashMap<>();
V get(@NonNull String key) { return map.get(key); }
}
static class Point {
final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
// explicit receiver parameter: lets you annotate "this"
boolean sameAs(@NonNull Point this, Point other) { return other != null && x == other.x && y == other.y; }
}
// type-use annotations in several positions
static List<@NonNull String> names = List.of("a", "b");
static @NonNull String[][] cells; // cells[i][j] are non-null
static String @NonNull [][] grid; // grid itself is non-null
static String[] @NonNull [] rows; // rows[i] is non-null
static class Warning extends @Localized Object implements @Localized Comparable<Warning> {
public int compareTo(Warning o) { return 0; }
}
public static void main(String[] args) throws Exception {
System.out.println("-- a tool finds annotated methods --");
for (Method m : sorted(CacheTest.class.getDeclaredMethods())) {
var anns = new ArrayList<String>();
for (Annotation a : m.getDeclaredAnnotations()) anns.add(a.annotationType().getSimpleName());
if (!anns.isEmpty()) System.out.println(" " + m.getName() + " " + anns);
}
System.out.println("-- elements, defaults and shortcuts --");
RepeatedTest r1 = CacheTest.class.getDeclaredMethod("retriesDefault").getAnnotation(RepeatedTest.class);
RepeatedTest r2 = CacheTest.class.getDeclaredMethod("retriesThree").getAnnotation(RepeatedTest.class);
System.out.println(" @RepeatedTest(10): value=" + r1.value() + ", failureThreshold=" + r1.failureThreshold() + " (default)");
System.out.println(" @RepeatedTest(value=10, failureThreshold=3): " + r2.value() + ", " + r2.failureThreshold());
BugReport b = CacheTest.class.getDeclaredMethod("buggy").getAnnotation(BugReport.class);
System.out.println(" showStopper=" + b.showStopper() + ", assignedTo=" + b.assignedTo() + ", testCase=" + b.testCase().getSimpleName()
+ ", status=" + b.status() + ", ref.id=" + b.ref().id() + ", reportedBy=" + Arrays.toString(b.reportedBy()));
BugReport minor = CacheTest.class.getDeclaredMethod("minorBug").getAnnotation(BugReport.class);
System.out.println(" @BugReport(reportedBy=\"Omar\"): reportedBy=" + Arrays.toString(minor.reportedBy())
+ ", status=" + minor.status() + ", assignedTo=" + minor.assignedTo());
System.out.println("-- repeated annotations --");
Method hello = CacheTest.class.getDeclaredMethod("testHello");
System.out.println(" tags: " + Arrays.stream(hello.getAnnotationsByType(Tag.class)).map(Tag::value).toList());
System.out.println(" stored in container @Tags: " + (hello.getAnnotation(Tags.class) != null)
+ ", getAnnotation(Tag.class) = " + hello.getAnnotation(Tag.class));
System.out.println("-- declarations: record components, parameters, type parameters --");
RecordComponent width = Tile.class.getRecordComponents()[0];
System.out.println(" record component " + width.getName() + ": " + width.getAnnotation(Label.class).value());
System.out.println(" propagated to the field: " + (Tile.class.getDeclaredField("width").getAnnotation(Label.class) != null)
+ ", to the accessor: " + (Tile.class.getDeclaredMethod("width").getAnnotation(Label.class) != null));
Method get = Cache.class.getDeclaredMethod("get", String.class);
System.out.println(" parameter of get: " + get.getParameters()[0].isAnnotationPresent(NonNull.class));
System.out.println(" type parameter V: " + Cache.class.getTypeParameters()[0].isAnnotationPresent(NonNull.class));
System.out.println("-- type uses --");
var argType = (AnnotatedParameterizedType) Solution.class.getDeclaredField("names").getAnnotatedType();
AnnotatedType stringArg = argType.getAnnotatedActualTypeArguments()[0];
System.out.println(" List<@NonNull String>: type argument annotated: " + stringArg.isAnnotationPresent(NonNull.class));
for (String f : List.of("cells", "grid", "rows")) System.out.println(" " + f + ": " + describeArray(Solution.class.getDeclaredField(f).getAnnotatedType()));
System.out.println(" superclass annotated: " + Warning.class.getAnnotatedSuperclass().isAnnotationPresent(Localized.class)
+ ", interface annotated: " + Warning.class.getAnnotatedInterfaces()[0].isAnnotationPresent(Localized.class));
Method sameAs = Point.class.getDeclaredMethod("sameAs", Point.class);
System.out.println(" receiver parameter annotated: " + sameAs.getAnnotatedReceiverType().isAnnotationPresent(NonNull.class)
+ ", parameter count: " + sameAs.getParameterCount());
System.out.println(" sameAs works: " + new Point(1, 2).sameAs(new Point(1, 2)));
Object text = "hello";
if (text instanceof @Localized String s) System.out.println(" instanceof with a type annotation: " + s.length());
}
static String describeArray(AnnotatedType t) {
var parts = new ArrayList<String>();
while (true) {
parts.add((t.isAnnotationPresent(NonNull.class) ? "@NonNull " : "") + t.getType().getTypeName());
if (t instanceof AnnotatedArrayType at) t = at.getAnnotatedGenericComponentType(); else break;
}
return String.join(" -> ", parts);
}
static Method[] sorted(Method[] ms) {
Arrays.sort(ms, Comparator.comparing(Method::getName));
return ms;
}
}
-- a tool finds annotated methods --
buggy [BugReport]
checkRandomInsertions [Test]
minorBug [BugReport]
retriesDefault [RepeatedTest]
retriesThree [RepeatedTest]
testHello [Test, Tags]
-- elements, defaults and shortcuts --
@RepeatedTest(10): value=10, failureThreshold=2147483647 (default)
@RepeatedTest(value=10, failureThreshold=3): 10, 3
showStopper=true, assignedTo=Omar, testCase=CacheTest, status=CONFIRMED, ref.id=11235811, reportedBy=[Omar, Fred]
@BugReport(reportedBy="Omar"): reportedBy=[Omar], status=UNCONFIRMED, assignedTo=[none]
-- repeated annotations --
tags: [localized, showstopper]
stored in container @Tags: true, getAnnotation(Tag.class) = null
-- declarations: record components, parameters, type parameters --
record component width: width in px
propagated to the field: true, to the accessor: true
parameter of get: true
type parameter V: true
-- type uses --
List<@NonNull String>: type argument annotated: true
cells: java.lang.String[][] -> java.lang.String[] -> @NonNull java.lang.String
grid: @NonNull java.lang.String[][] -> java.lang.String[] -> java.lang.String
rows: java.lang.String[][] -> @NonNull java.lang.String[] -> java.lang.String
superclass annotated: true, interface annotated: true
receiver parameter annotated: true, parameter count: 1
sameAs works: true
instanceof with a type annotation: 5
Common questions
Do annotations change what my code does?
Not by themselves. The compiler produces the same instructions with or without them. They take effect only when a tool reads them: the compiler for @Override, a framework through reflection, an annotation processor at compile time, or a bytecode tool.
Why can't I use a variable as an annotation value?
Annotation values must be compile-time constants, because the compiler stores them in the class file. Literals, static final constants, class literals, enum constants and other annotations are allowed. A method call or ordinary variable is not.
What is the difference between a declaration annotation and a type-use annotation?
A declaration annotation describes the declared item, such as a method, field or parameter. A type-use annotation describes one use of a type, as in List<@NonNull String>, where it applies to the list's elements. Type-use annotations need ElementType.TYPE_USE in their @Target.
Which nullness annotations should I use?
For new code, JSpecify's @Nullable and @NonNull (org.jspecify.annotations) are the emerging common standard, understood by NullAway, IntelliJ IDEA, Kotlin and others. The JDK itself has no nullness annotations.
Can I see a local variable's annotation through reflection? No. Declaration annotations on local variables are never written to the class file. Only source-level tools such as annotation processors and the compiler can see them.
Summary
- Annotations are tags for tools such as the compiler, test frameworks, persistence and dependency-injection frameworks, static checkers and code generators. They don't change the generated code by themselves.
- Elements hold primitives, strings,
Classobjects, enums, annotations or one-dimensional arrays of these. Values must be compile-time constants and nevernull. Defaults, thevalueshortcut and brace-less single-element arrays keep usage short. - Annotations can be combined, and repeatable ones can be used several times. The compiler stores repeats in a container annotation.
- Declaration annotations go on classes, methods, constructors, fields, record components, variables, parameters, type parameters, packages (
package-info.java) and modules. Declaration annotations on local variables never reach the class file. - Type-use annotations describe uses of types: type arguments, array levels, supertypes, casts,
instanceof,throws, bounds and method references. An explicit receiver parameterType thislets you annotatethis.
Practice Questions
Why is @Author(name = someVariable) illegal?
Annotation element values must be compile-time constants, because the compiler evaluates them and stores them in the class file. A variable's value isn't known until runtime. A static final constant initialized with a constant expression is allowed.
When can you omit "value =" in an annotation?
When the element is named value and it's the only element you supply. All other elements must have defaults or be omitted. For example, @SuppressWarnings("unchecked") or @RepeatedTest(10).
What do these three declarations say? @NonNull String[][] a; String @NonNull [][] b; String[] @NonNull [] c;
In a, the String elements a[i][j] are non-null. In b, the array b itself is non-null. In c, each row c[i] is non-null. The annotation applies to the array level, or the element type, at the position where it's written.
Where do you put an annotation for a package, and what is unusual about the imports?
In a file named package-info.java in the package's directory, before the package statement. Any import for the annotation type comes after the package statement, as in every Java file, even though the annotation appears above it.
What is a receiver parameter, and can a constructor have one?
It's an explicit declaration of this as the first parameter, written as Type this, so that you can annotate it. It doesn't change how the method is called. Constructors can't have one. Inner-class constructors can declare the outer instance as Outer Outer.this.
Previous: Java Processes and ProcessBuilder: Running and Managing External Programs
Next: Defining Custom Java Annotations: @interface, Elements, Retention and Target
Related reading
- Java Processes and ProcessBuilder: Running and Managing External Programs
- Java Long-Running Tasks in User Interfaces: Swing Worker Threads and Callbacks
- Java CompletableFuture: Asynchronous Programming with Callbacks and Composition
- Java ConcurrentHashMap, CopyOnWriteArrayList and Parallel Array Algorithms
- Java Blocking Queues and Thread-Safe Collections: Producer-Consumer Made Easy

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.