Reflection & Java Doc ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-12-04

Java Annotations: Built-in and Custom

A Java annotation is metadata attached to a declaration (a class, interface, method, constructor, field, parameter, local variable, package or module) or to a use of a type. An annotation does not change code by itself: it is read by the compiler (@Override), by annotation processors at compile time (Lombok, MapStruct) and by frameworks through reflection at runtime (JUnit finds methods marked @Test, Spring finds beans, JPA finds entities). You write an annotation as @Name, @Name(value) or @Name(key = value). Annotations were introduced in Java 5 (JSR 175).

Your first custom annotation almost always «doesn’t work»: it is right there in the code, yet reflection cannot see it.

// HookDemo.java
@interface Test {}   // no @Retention

public class HookDemo {
    @Test
    void checkSum() {}

    public static void main(String[] args) throws Exception {
        var m = HookDemo.class.getDeclaredMethod("checkSum");
        System.out.println(m.isAnnotationPresent(Test.class)); // false
    }
}

No compile error, no exception — just false. Without @Retention(RetentionPolicy.RUNTIME) the annotation stays in the .class file, but the JVM does not load it for reflection. The reason is explained in the @Retention section.

1. Syntax: where and how annotations are written

An annotation goes before a declaration, like a modifier: @Override public String toString(). You can put it on a class, interface, enum, record and its components, method, constructor, field, parameter, local variable, package and module, and since Java 8 also on a use of a type: List<@NonEmpty String>. Where a particular annotation is allowed is decided by its @Target meta-annotation.

// WherePlaced.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.util.List;

@interface Note {                 // no @Target: fits any declaration
    String value() default "";
}

@Target(ElementType.TYPE_USE)
@interface NonEmpty {}            // type use only (Java 8+)

@Note("class")
public class WherePlaced {
    @Note("field")
    private int count;

    @Note("constructor")
    public WherePlaced() {}

    @Note("method")
    void process(@Note("parameter") String input) {
        @Note("local variable") int length = input.length();
        List<@NonEmpty String> names = List.of(input);    // annotation on a type
        Object o = (@NonEmpty String) input;               // and in a cast
        System.out.println(length + " " + names + " " + o);
    }

    @Note("enum")
    enum Status { NEW, PAID }

    @Note("record")
    record Item(@Note("record component") String name) {}

    public static void main(String[] args) {
        new WherePlaced().process("Java");
    }
}
4 [Java] Java

Package annotations go into a separate package-info.java file before the package line, module annotations into module-info.java before module. One declaration can carry several different annotations in any order; the same annotation twice is allowed only if it is repeatable.

Element values are passed in parentheses. There are four forms:

@Override                                    // marker: no elements, no parentheses
@SuppressWarnings("unchecked")               // single element value: the name can be omitted
@Deprecated(since = "9", forRemoval = true)  // name = value pairs separated by commas
@SuppressWarnings({"unchecked", "rawtypes"}) // array in curly braces

The short form without a name works only for an element called value, and only when no other elements are specified (they must have defaults). If an array has a single element, the braces are optional: @SuppressWarnings("unchecked") and @SuppressWarnings({"unchecked"}) mean the same thing.

2. Built-in annotations in Java

The java.lang package contains five annotations handled by the compiler itself: @Override, @Deprecated, @SuppressWarnings, @SafeVarargs and @FunctionalInterface. Each one turns an agreement you used to keep in your head into a javac check: a compile error or a warning.

Annotation Where it goes What the compiler does Retention Since
@Override Method Error if the method neither overrides nor implements anything SOURCE Java 5
@Deprecated Class, method, constructor, field, parameter, local variable, package, module Warning when the element is used; forRemoval = true gives a [removal] warning RUNTIME Java 5; since, forRemoval — Java 9
@SuppressWarnings Any declaration Turns off the listed warnings inside the element SOURCE Java 5
@SafeVarargs Constructor; static, final or private (Java 9+) method with varargs Removes unchecked warnings about generic varargs; error on an overridable method RUNTIME Java 7
@FunctionalInterface Interface Error unless there is exactly one abstract method RUNTIME Java 8

@Override

@Override asks the compiler to check that the method really overrides a superclass method or implements an interface method. The classic mistake is equals taking your own type instead of Object:

// Point.java
public class Point {
    private final int x;
    private final int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public boolean equals(Point other) {
        return x == other.x && y == other.y;
    }
}
Point.java:11: error: method does not override or implement a method from a supertype
    @Override
    ^
1 error

Without the annotation the code would compile, but you would get an overloaded equals(Point), while HashSet and List.contains() would keep calling equals(Object) from Object. The difference between overloading and overriding is covered in Method Overloading vs Overriding.

@Deprecated: since and forRemoval

@Deprecated marks API that should no longer be used. Since Java 9 the annotation has two elements: since — the version in which the element became deprecated, and forRemoval — whether it is going to be removed. forRemoval decides how loudly the compiler complains.

// Old.java
public class Old {
    /** @deprecated use {@link #c()} instead */
    @Deprecated(since = "9")
    public static void a() {}

    /** @deprecated will be removed; use {@link #c()} instead */
    @Deprecated(since = "9", forRemoval = true)
    public static void b() {}

    public static void c() {}
}
// Use.java
public class Use {
    public static void main(String[] args) {
        Old.a();   // deprecated
        Old.b();   // deprecated and marked for removal
        Old.c();
    }
}

The command javac Old.java Use.java without flags prints:

Use.java:5: warning: [removal] b() in Old has been deprecated and marked for removal
        Old.b();   // deprecated and marked for removal
           ^
Note: Use.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 warning

The [removal] warning is on by default and appears at every call. Plain deprecation produces only a summary Note line: to see which call is deprecated, add -Xlint:deprecation — then you also get warning: [deprecation] a() in Old has been deprecated, 2 warnings in total. Inside the very class that declares the deprecated element there are no warnings.

@Deprecated vs @deprecated

The @Deprecated annotation with a capital D gets into the bytecode and switches on compiler warnings. The lowercase @deprecated Javadoc tag lives only in the comment and tells a human what to use instead. Use them together, as in Old.java; the tag is described in the Javadoc tags table.

@SuppressWarnings: unchecked, deprecation and other values

@SuppressWarnings turns off the listed compiler warnings inside the annotated element and everything nested in it. An unknown warning name is not an error: the compiler is required to ignore it.

// SuppressDemo.java
import java.util.List;

public class SuppressDemo {
    public static void main(String[] args) {
        Object data = List.of("a", "b");

        @SuppressWarnings("unchecked")      // only for this variable
        List<String> list = (List<String>) data;

        System.out.println(list.get(0).toUpperCase());
    }
}
A

Without the annotation the code would compile with the message Note: SuppressDemo.java uses unchecked or unsafe operations. (plus the hint Recompile with -Xlint:unchecked for details.): because of type erasure, the cast from Object to List<String> is not checked at runtime.

The specification (JLS 9.6.4.5) requires every compiler to recognize four values: "unchecked", "deprecation", "removal" and "preview". The rest — "rawtypes", "serial", "unused", "all" and so on — depend on the compiler and the IDE; the list javac understands is printed by javac --help-lint.

Put the annotation on the narrowest scope possible: on a local variable declaration rather than the method, on the method rather than the class. @SuppressWarnings("all") on a whole class also hides warnings about code that someone writes later.

@SafeVarargs

@SafeVarargs is the programmer’s promise that a method with a parameter like T... or List<String>... does nothing dangerous with the argument array. In return the compiler stops reporting heap pollution at the declaration and generic array creation at call sites.

// SafeVarargsDemo.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SafeVarargsDemo {
    @SafeVarargs
    static <T> List<T> listOf(T... items) {
        return new ArrayList<>(Arrays.asList(items));
    }

    public static void main(String[] args) {
        List<List<String>> nested = listOf(List.of("a"), List.of("b", "c"));
        System.out.println(nested);
    }
}
[[a], [b, c]]

The annotation is allowed only where the method cannot be overridden: on constructors, static and final methods and, since Java 9, private methods. Otherwise a subclass could override a «safe» method with an unsafe implementation. On a regular instance method it is a compile error:

// Box.java
public class Box<T> {
    @SafeVarargs
    public void addAll(T... items) {}   // not static, not final, not private
}
Box.java:4: error: Invalid SafeVarargs annotation. Instance method addAll(T...) is neither final nor private.
    public void addAll(T... items) {}   // not static, not final, not private
                ^
  where T is a type-variable:
    T extends Object declared in class Box
1 error

What heap pollution is and why generic varargs trigger a warning in the first place is explained in Varargs: Variable-Length Arguments.

@FunctionalInterface

@FunctionalInterface checks that an interface has exactly one abstract method — that is, it can be implemented with a lambda. default and static methods don’t count, and neither do abstract methods matching public methods of Object (equals, toString). Add a second abstract method and javac reports error: Unexpected @FunctionalInterface annotation with the explanation multiple non-overriding abstract methods found in interface .... The annotation is optional, but it protects the interface from being extended by accident; examples are in Functional Interfaces.

3. Meta-annotations: @Retention, @Target, @Inherited, @Repeatable

Meta-annotations are annotations from the java.lang.annotation package that you put on the declaration of another annotation to set its properties: how long it is kept, where it can be used, whether it is inherited, whether it shows up in Javadoc and whether it can be repeated. The built-in annotations are declared with them — @Override, for example, carries @Retention(SOURCE) and @Target(METHOD).

Meta-annotation What it sets If omitted Since
@Retention Where the annotation is kept: source only, the .class file, or available at runtime RetentionPolicy.CLASS — reflection does not see the annotation Java 5
@Target Where the annotation may be used (ElementType) Any declaration, but not a type use Java 5
@Documented Show the annotation in generated Javadoc The annotation is not visible in the docs Java 5
@Inherited An annotation on a class also applies to its subclasses Not inherited Java 5
@Repeatable Can be used several times on one declaration Repeating it is a compile error Java 8

@Retention: SOURCE, CLASS, RUNTIME

@Retention defines how far an annotation survives. SOURCE — source code only, the compiler discards it. CLASS — written to the .class file, but the JVM does not load it at runtime; this is the default. RUNTIME — available through reflection while the program runs.

// RetentionDemo.java
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;

@Retention(RetentionPolicy.SOURCE)
@interface OnlySource {}

@Retention(RetentionPolicy.CLASS)
@interface InClassFile {}

@Retention(RetentionPolicy.RUNTIME)
@interface AtRuntime {}

@OnlySource
@InClassFile
@AtRuntime
public class RetentionDemo {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(RetentionDemo.class.getAnnotations()));
        System.out.println(RetentionDemo.class.isAnnotationPresent(InClassFile.class));
    }
}
[@AtRuntime()]
false

Reflection sees one of the three annotations. So who needs the other two? SOURCE is enough for anything that works at compile time: @Override, @SuppressWarnings, processors such as Lombok. CLASS is for tools that read bytecode directly without loading classes — analyzers and instrumentation tools. Frameworks and your own reflection-based handlers need RUNTIME.

@Target and ElementType

@Target lists where an annotation may be used, as constants of the ElementType enum. Without @Target an annotation fits any declaration, but not a type use — List<@X String> requires an explicit TYPE_USE.

ElementType Where it goes Since
TYPE Class, interface (including an annotation), enum, record Java 5
FIELD Field, enum constant Java 5
METHOD Method Java 5
PARAMETER Method or constructor parameter Java 5
CONSTRUCTOR Constructor Java 5
LOCAL_VARIABLE Local variable Java 5
ANNOTATION_TYPE Annotation declaration (this is how meta-annotations are declared) Java 5
PACKAGE Package (package-info.java) Java 5
TYPE_PARAMETER Type parameter: class Box<@X T> Java 8
TYPE_USE Any use of a type: List<@X String>, (@X String) o, new @X Foo() Java 8
MODULE Module (module-info.java) Java 9
RECORD_COMPONENT A record component Java 16

Put an annotation in the wrong place and compilation fails:

// TargetError.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@interface Command {}

@Command                      // a class, but only methods are allowed
public class TargetError {}
TargetError.java:8: error: annotation interface not applicable to this kind of declaration
@Command                      // a class, but only methods are allowed
^
1 error

The same constant listed twice in @Target (@Target({FIELD, METHOD, FIELD})) is also a compile error.

@Documented

@Documented tells the javadoc command to show the annotation in the signature of the annotated element on the HTML page. @Deprecated and @FunctionalInterface are declared this way, so a reader of the documentation sees them next to the method. Your own annotation needs @Documented if it is part of the public API contract (for example, @ThreadSafe). How to generate documentation is covered in Javadoc in Java.

@Inherited

@Inherited makes an annotation on a class visible on its subclasses: if a class does not have the annotation, getAnnotation() looks for it on the superclass, then further up to Object. This works for classes only: annotations on interfaces, methods and fields are not inherited, even if the annotation is marked @Inherited.

// InheritedDemo.java
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@interface Entity {}

@Retention(RetentionPolicy.RUNTIME)
@interface Audited {}             // no @Inherited

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@interface Plugin {}

@Entity
@Audited
class BaseModel {}

class User extends BaseModel {}

@Plugin
interface Extension {}

class PdfExtension implements Extension {}

public class InheritedDemo {
    public static void main(String[] args) {
        System.out.println(User.class.isAnnotationPresent(Entity.class));          // true
        System.out.println(User.class.isAnnotationPresent(Audited.class));         // false
        System.out.println(User.class.getDeclaredAnnotations().length);            // 0
        System.out.println(PdfExtension.class.isAnnotationPresent(Plugin.class));  // false
    }
}
true
false
0
false

The last line surprises people most: @Plugin is marked @Inherited, but it sits on an interface, and implementations of an interface do not get the annotation. Look at the third line too: getDeclaredAnnotations() returns only annotations declared directly on the class, so inherited ones are not included.

@Repeatable: repeating annotations

@Repeatable (Java 8) lets you put the same annotation on a declaration several times. It requires a containing annotation whose value element is an array of the repeatable one: at compile time several @Schedule annotations are wrapped into a single @Schedules.

What does this code print?

// RepeatableDemo.java
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;

@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Schedules.class)
@interface Schedule {
    String value();
}

@Retention(RetentionPolicy.RUNTIME)
@interface Schedules {            // container
    Schedule[] value();
}

@Schedule("mon")
@Schedule("fri")
class Backup {}

@Schedule("mon")
class Report {}

public class RepeatableDemo {
    public static void main(String[] args) {
        System.out.println(Backup.class.getAnnotation(Schedule.class));
        System.out.println(Arrays.toString(Backup.class.getAnnotationsByType(Schedule.class)));
        System.out.println(Backup.class.getAnnotation(Schedules.class));

        System.out.println(Arrays.toString(Report.class.getAnnotationsByType(Schedule.class)));
        System.out.println(Report.class.getAnnotation(Schedules.class));
    }
}
null
[@Schedule("mon"), @Schedule("fri")]
@Schedules({@Schedule("mon"), @Schedule("fri")})
[@Schedule("mon")]
null

With two repetitions, the Backup class physically carries one annotation — the @Schedules container — so getAnnotation(Schedule.class) returns null. Report has a single annotation, no container is created, and the picture is reversed. getAnnotationsByType() looks inside the container and behaves the same in both cases — use it for repeatable annotations.

4. How to create a custom annotation

A custom annotation is declared with the @interface keyword. Its elements are written as methods without parameters: the return type is the element type, and the default value follows the default keyword. To make the annotation readable through reflection, add @Retention(RetentionPolicy.RUNTIME); to restrict where it can be used, add @Target.

// CustomAnnotationDemo.java
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Arrays;

enum Priority { LOW, MEDIUM, HIGH }

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@interface Task {
    String value();                               // required element
    Priority priority() default Priority.MEDIUM;  // enum
    String[] tags() default {};                   // array
    int estimateHours() default 1;                // primitive
    Class<?> owner() default Object.class;        // class
}

@Task(value = "Payment module", priority = Priority.HIGH, tags = {"payments", "api"})
public class CustomAnnotationDemo {

    @Task("Logging")                              // value without a name, the rest by default
    void log() {}

    public static void main(String[] args) throws Exception {
        Task t = CustomAnnotationDemo.class.getAnnotation(Task.class);
        System.out.println(t.value() + ", " + t.priority() + ", "
                + Arrays.toString(t.tags()) + ", " + t.estimateHours());

        Task m = CustomAnnotationDemo.class.getDeclaredMethod("log").getAnnotation(Task.class);
        System.out.println(m.value() + ", " + m.priority() + ", " + m.tags().length);

        System.out.println(t instanceof Annotation);
        System.out.println(t.annotationType().getSimpleName());
    }
}
Payment module, HIGH, [payments, api], 1
Logging, MEDIUM, 0
true
Task

Element values are read by calling the methods of the same name: t.priority(). An annotation without elements (@interface Test {}) is called a marker annotation; an annotation with a single value element is a single-element annotation.

Element types are restricted. The compiler has to write the value into the .class file as a constant, so arbitrary objects won’t do:

Element type Allowed? Example
Primitives (int, long, boolean, double…) Yes int max() default 100;
String Yes String message() default "";
Class, Class<?>, Class<? extends X> Yes Class<? extends Throwable> expected();
enum Yes Priority priority();
Another annotation Yes Schedule[] value();
One-dimensional array of any of these types Yes String[] tags() default {};
Wrappers (Integer), Object, List, your own classes No compile error
Two-dimensional array int[][] No compile error

Other restrictions:

  • an element value must be a compile-time constant: a literal, a static final constant, a class literal, an enum constant. A method call (LocalDate.now()) won’t compile;
  • null is forbidden both as a value and as a default: String name() default null; does not compile. To express «no value», use an empty string, an empty array or a special marker class, like Test.None in the example below;
  • an element has no parameters and no throws clause;
  • an annotation cannot use extends and cannot be generic: every annotation implicitly extends the java.lang.annotation.Annotation interface, and only that one.
// BadAnnotation.java — does not compile
@interface BadAnnotation {
    Object data();                 // invalid type
    String name() default null;    // null is not allowed
    int[][] matrix();              // one-dimensional arrays only
}
BadAnnotation.java:4: error: element value must be a constant expression
    String name() default null;    // null is not allowed
                          ^
BadAnnotation.java:3: error: invalid type for annotation interface element
    Object data();                 // invalid type
    ^
BadAnnotation.java:5: error: invalid type for annotation interface element
    int[][] matrix();              // one-dimensional arrays only
       ^
3 errors

5. Reading annotations with reflection

Annotations with @Retention(RUNTIME) are read through the methods of the java.lang.reflect.AnnotatedElement interface. It is implemented by Class, Method, Field, Constructor, Parameter, Package and RecordComponent, so you look up an annotation on a class, a method or a parameter the same way. How to get the methods and fields themselves is covered in Java Reflection API: the Class Object.

Method What it returns Honors @Inherited Sees repeatable annotations
getAnnotation(Class<A>) The annotation or null Yes No — null when repeated
isAnnotationPresent(Class) getAnnotation(...) != null Yes No
getAnnotations() All annotations, an empty array if none Yes Container only
getDeclaredAnnotations() Annotations declared directly on the element No Container only
getAnnotationsByType(Class<A>) Array of annotations of the type, including those inside a container Yes Yes
getDeclaredAnnotation(Class), getDeclaredAnnotationsByType(Class) The same, without inherited ones No Same as the non-Declared pair

For methods, fields and constructors there is no difference between the get and getDeclared versions: @Inherited works only on classes. Parameter annotations are returned by Method.getParameterAnnotations() — a two-dimensional array, one array per parameter.

Example: a mini JUnit with a custom @Test annotation

JUnit finds tests by the @Test annotation, not by method name. Let’s build the same mechanism: an annotation with an expected element (which exception the test must throw) and a runner that finds the annotated methods and calls them.

// MiniJUnit.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Comparator;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Test {
    Class<? extends Throwable> expected() default None.class;

    final class None extends Throwable {     // marker: "no exception expected"
        private None() {}
    }
}

class CalculatorTests {
    @Test
    void addition() {
        check(2 + 2 == 4);
    }

    @Test
    void division() {
        check(10 / 3 == 3);
    }

    @Test(expected = ArithmeticException.class)
    void divideByZero() {
        int zero = 0;
        System.out.println(1 / zero);
    }

    @Test
    void wrongSum() {
        check(0.1 + 0.2 == 0.3);
    }

    @Test(expected = IllegalArgumentException.class)
    void noException() {
    }

    void helper() {                          // no @Test: the runner skips it
        throw new IllegalStateException("must not be called");
    }

    static void check(boolean condition) {
        if (!condition) {
            throw new AssertionError("condition failed");
        }
    }
}

public class MiniJUnit {
    public static void main(String[] args) throws Exception {
        Class<?> testClass = CalculatorTests.class;
        Method[] methods = testClass.getDeclaredMethods();
        Arrays.sort(methods, Comparator.comparing(Method::getName)); // order is not guaranteed

        int passed = 0;
        int failed = 0;
        for (Method method : methods) {
            Test test = method.getAnnotation(Test.class);
            if (test == null) {
                continue;
            }
            Object instance = testClass.getDeclaredConstructor().newInstance(); // new object for every test
            try {
                method.invoke(instance);
                if (test.expected() == Test.None.class) {
                    System.out.println("PASSED " + method.getName());
                    passed++;
                } else {
                    System.out.println("FAILED " + method.getName()
                            + ": expected " + test.expected().getSimpleName());
                    failed++;
                }
            } catch (InvocationTargetException e) {
                Throwable cause = e.getCause();      // the real exception from the test
                if (test.expected().isInstance(cause)) {
                    System.out.println("PASSED " + method.getName());
                    passed++;
                } else {
                    System.out.println("FAILED " + method.getName() + ": " + cause);
                    failed++;
                }
            }
        }
        System.out.println("Total: " + passed + " passed, " + failed + " failed");
    }
}
PASSED addition
PASSED divideByZero
PASSED division
FAILED noException: expected IllegalArgumentException
FAILED wrongSum: java.lang.AssertionError: condition failed
Total: 3 passed, 2 failed

The runner rests on three details. The expected element cannot be null, so «nothing expected» is expressed with the Test.None marker class — the same trick JUnit 4 uses. An exception from the test arrives wrapped in InvocationTargetException, and you have to check getCause(). The check method is declared in the class too, but it has no annotation, so the runner skips it, just like helper. The wrongSum test fails for real: in double, 0.1 + 0.2 is not equal to 0.3.

Example: a field validator driven by annotations

Bean Validation (@NotNull, @Size in Spring and Jakarta EE) works on the same principle: annotations on fields describe the rules, and separate code reads them and checks the values.

// ValidatorDemo.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface NotBlank {
    String message() default "must not be blank";
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Max {
    int value();
}

class UserForm {
    @NotBlank
    private String login;

    @NotBlank(message = "enter an e-mail")
    private String email;

    @Max(120)
    private int age;

    private String comment;                  // no annotations: not checked

    UserForm(String login, String email, int age) {
        this.login = login;
        this.email = email;
        this.age = age;
    }
}

public class ValidatorDemo {
    static List<String> validate(Object obj) throws IllegalAccessException {
        List<String> errors = new ArrayList<>();
        for (Field field : obj.getClass().getDeclaredFields()) {
            field.setAccessible(true);           // the fields are private
            Object value = field.get(obj);

            NotBlank notBlank = field.getAnnotation(NotBlank.class);
            if (notBlank != null && (value == null || value.toString().isBlank())) {
                errors.add(field.getName() + ": " + notBlank.message());
            }

            Max max = field.getAnnotation(Max.class);
            if (max != null && ((Number) value).intValue() > max.value()) {
                errors.add(field.getName() + ": must be at most " + max.value());
            }
        }
        Collections.sort(errors);                // field order is not guaranteed
        return errors;
    }

    public static void main(String[] args) throws IllegalAccessException {
        System.out.println(validate(new UserForm("  ", null, 150)));
        System.out.println(validate(new UserForm("tanya", "t@example.com", 30)));
    }
}
[age: must be at most 120, email: enter an e-mail, login: must not be blank]
[]

Note that the annotations check nothing on their own. If nobody calls validate(), an object with a blank login lives on happily. How setAccessible(true) and Field.get() work is shown in invoking methods and accessing fields.

6. Annotation processing at compile time

A Java annotation processor is a subclass of javax.annotation.processing.AbstractProcessor that javac runs during compilation. It receives the elements carrying the annotations it handles and can report an error or a warning, or generate new source files. Reflection plays no part here, so @Retention(SOURCE) is enough for such annotations.

Popular tools are built on processors: Lombok removes boilerplate based on @Getter and @Builder, MapStruct generates mappers between DTOs and entities, Dagger generates dependency injection code, AutoValue generates value classes. Mistakes in these annotations show up at build time rather than at startup, and there is no reflection cost at runtime.

A minimal processor prints a note for every element annotated with @Todo:

// Todo.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Todo {
    String value();
}
// TodoProcessor.java
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;

@SupportedAnnotationTypes("Todo")
public class TodoProcessor extends AbstractProcessor {

    @Override
    public SourceVersion getSupportedSourceVersion() {
        return SourceVersion.latestSupported();
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
        for (Element element : env.getElementsAnnotatedWith(Todo.class)) {
            String text = element.getAnnotation(Todo.class).value();
            processingEnv.getMessager()
                    .printMessage(Diagnostic.Kind.NOTE, "TODO: " + text, element);
        }
        return true;
    }
}
// App.java
@Todo("add validation") public class App {
    public static void main(String[] args) {
        System.out.println("App");
    }
}

First compile the annotation and the processor, then the code, naming the processor explicitly:

javac Todo.java TodoProcessor.java
javac -processor TodoProcessor App.java
App.java:2: Note: TODO: add validation
@Todo("add validation") public class App {
                               ^

JDK 23+: processors no longer run on their own

javac used to find a processor on the classpath through the META-INF/services/javax.annotation.processing.Processor file and run it without asking. Since JDK 23 that no longer happens: unless you pass -processor, --processor-path (--processor-module-path) or -proc:full, the processor is silently skipped — no error, no warning. JDK 21–22 only printed a warning about it. If Lombok stopped working after a JDK upgrade, check that it is configured as an annotation processor in your Maven or Gradle build.

7. Annotation, marker interface, Javadoc tag or XML

An annotation is not the only way to mark code. The right choice depends on who reads the mark: the compiler through the type system, a human, a framework at runtime, or an administrator who must change it without recompiling.

Approach Example Strengths When to choose it
Annotation @Test, @Entity Goes on methods, fields, parameters; carries parameters; read by the compiler, a processor or reflection Metadata for tools and frameworks
Marker interface Serializable, Cloneable It is a type: you can write a method that accepts only Serializable and check with instanceof Marking a class when the type system must enforce the mark
Javadoc tag @deprecated, @since Free text for humans Explanations in the documentation; never reaches the bytecode
External configuration (XML, YAML) web.xml, persistence.xml Changes without recompiling; the code does not depend on the library Settings that differ between environments

A marker interface and an annotation are not interchangeable. The interface is inherited by every subclass without exception and takes part in parameter types; an annotation can go on anything, but the compiler won’t stop you from passing an unmarked object to a method.

8. Where developers slip up with annotations

Most annotation problems are silent: the code compiles, there are no exceptions, and the annotation simply has no effect. The table collects these cases along with a couple of compile errors that tend to surprise beginners.

Mistake What happens How to fix it
A custom annotation without @Retention(RUNTIME) isAnnotationPresent() returns false, getAnnotation() returns null Add @Retention(RetentionPolicy.RUNTIME) — see @Retention
An @Inherited annotation on an interface or a method Implementations and overriding methods don’t see it Look the annotation up explicitly via getInterfaces() or on the superclass method
getAnnotation() for a repeatable annotation null if the annotation is used two or more times getAnnotationsByType()
null as an element value or default Compile error An empty string, an empty array or a marker class
Being afraid to put @Override on an interface method implementation Allowed since Java 6 (it was an error in Java 5) Use it: it guards against typos in the name and signature
@SuppressWarnings("all") on a whole class Future warnings are hidden too, including [removal] A specific warning name on the narrowest scope
@SafeVarargs on a public non-final method Compile error Make the method static, final or private
Expecting an annotation to change behavior by itself Nothing happens: @NotBlank without a validator checks nothing Every annotation needs a handler: the compiler, a processor or reflection code

9. Annotation questions in interviews

In interviews and on the OCP exam, annotations are tested with questions about how the mechanism works, not about memorizing a list. The most frequent ones concern things you only notice when you run the code:

  • What retention do the built-in annotations have? @Override and @SuppressWarnings are SOURCE, so reflection will never find them: method.isAnnotationPresent(Override.class) is always false. @Deprecated, @FunctionalInterface and @SafeVarargs are RUNTIME.
  • What is an annotation object at runtime? An instance of a dynamic proxy that implements the annotation interface. Its getClass() returns a generated name such as $Proxy1 (the exact name depends on the JDK and the module), which is why the annotation type is obtained with annotationType().
  • Can you change an annotation value at runtime? No: elements are methods without setters, and the values are fixed at compile time.
  • Can an annotation have methods with a body, or fields? Methods with a body — no, only elements. Constants (int MAX = 10;) and nested types — yes, just like in an interface: see Test.None from the example above.
  • How does @Target(TYPE_USE) differ from TYPE? TYPE is a class declaration; TYPE_USE is any place where a type is used: a generic argument, a cast, new, throws. Nullness checkers such as the Checker Framework are built on it.

Frequently asked questions

How is an annotation different from a comment or Javadoc?

Comments and Javadoc tags are read by humans; the compiler throws them away. An annotation is part of the language syntax: the compiler checks its type and values, can write it to the .class file, and with RetentionPolicy.RUNTIME the program reads it through reflection. That is why @Deprecated produces a compiler warning, while the @deprecated tag only adds text to the documentation.

Can annotations be inherited?

An annotation declaration cannot extend another annotation: @interface A extends B does not compile, and every annotation implicitly extends only java.lang.annotation.Annotation. Inheritance in the other sense — from a superclass to a subclass — is enabled by the @Inherited meta-annotation, and only for annotations on classes. An example with an interface where it does not work is in the @Inherited section.

What is the default RetentionPolicy?

RetentionPolicy.CLASS: the annotation is written to the bytecode, but reflection does not see it. Reading it with getAnnotation() requires an explicit @Retention(RetentionPolicy.RUNTIME). A comparison of the three policies with program output is in the @Retention section.

Why write @Override if the code works without it?

Without @Override, a typo in the method name or a parameter type creates a new method instead of an override, and the code still compiles. With the annotation, the same typo becomes a compile error. Also, if the method is removed from the superclass or interface, @Override immediately points to every place that no longer overrides anything.

How do I get all methods of a class that have a given annotation?

Iterate over getDeclaredMethods() (or getMethods() if you also need inherited public methods) and keep those for which isAnnotationPresent(MyAnnotation.class) returns true; the annotation must have @Retention(RUNTIME). With the Stream API: Arrays.stream(c.getDeclaredMethods()).filter(m -> m.isAnnotationPresent(Test.class)).toList(). A complete runner is in the mini JUnit section.

Practice

Reinforce this lesson with hands-on tasks, each with a level and a time estimate.

All module tasks →

Comments

Please log in or register to have a possibility to add comment.