Java Annotations

An annotation is metadata attached to code: a class, method, field, parameter or type. Annotations do nothing by themselves; tools read them. The compiler reads some (@Override), annotation processors read others at build time, and frameworks such as JUnit and Spring read many at run time through reflection. This lesson covers the built-in annotations, how to declare your own, and how a program can read them.

Annotation Syntax

Names and Elements

An annotation starts with @ followed by its name, optionally with elements in parentheses. It is written before the declaration it annotates, usually on its own line.

@Override                                   // marker: no elements
@SuppressWarnings("unchecked")              // single element named value: the name may be omitted
@Deprecated(since = "2.0", forRemoval = true)   // named elements

Type Annotations

Since Java 8 annotations can also appear wherever a type is used (type annotations), for example List<@NonNull String>. The JDK defines no checker for such annotations; tools such as the Checker Framework provide them.

Built-in Annotations

The java.lang package defines the annotations that the compiler itself enforces:

AnnotationApplies toEffect
@OverridemethodsCompile error unless the method overrides or implements a supertype method.
@Deprecatedmost declarationsWarns callers; since and forRemoval (Java 9+) say when and whether it will disappear.
@SuppressWarningsmost declarationsSilences named compiler warnings ("unchecked", "removal", "deprecation") in that scope.
@FunctionalInterfaceinterfacesCompile error unless the interface has exactly one abstract method.
@SafeVarargsfinal, static or private methods; constructorsPromises that a generic varargs method does not misuse its array, silencing heap-pollution warnings at call sites.

Using Them Together

// The annotations the compiler itself understands.
import java.util.ArrayList;
import java.util.List;

class Legacy {
    /** @deprecated replaced by {@link #total(int...)} */
    @Deprecated(since = "2.0", forRemoval = true)
    static int sum(int a, int b) { return a + b; }

    @SafeVarargs                                   // promises no unsafe use of the varargs array
    static <T> List<T> listOf(T... items) {
        List<T> list = new ArrayList<>();
        for (T item : items) list.add(item);       // read the array; never store or expose it
        return list;
    }

    static int total(int... values) {
        int t = 0;
        for (int v : values) t += v;
        return t;
    }
}

@FunctionalInterface                               // compile error if it ever gains a 2nd abstract method
interface Greeter {
    String greet(String name);
}

class BuiltInAnnotations {
    @SuppressWarnings("removal")                   // we call sum() knowingly
    public static void main(String[] args) {
        System.out.println(Legacy.sum(2, 3));
        System.out.println(Legacy.total(2, 3, 4));
        System.out.println(Legacy.listOf("a", "b"));
        Greeter g = name -> "Hello, " + name;
        System.out.println(g.greet("Ana"));
    }

    @Override                                      // checked: toString really exists in Object
    public String toString() { return "BuiltInAnnotations"; }
}

Output:

5
9
[a, b]
Hello, Ana

Keep @SuppressWarnings as narrow as possible — on one method or one local variable, never a whole class — and only after you have checked that the warning is a false alarm. A suppressed warning is a decision another reader should be able to find.

Declaring Your Own Annotations

An annotation type is declared with @interface. Its elements look like methods without parameters; each may have a default. Element types are limited to primitives, String, Class, enums, other annotations, and arrays of these.

Meta-annotations

Annotations on an annotation type control how it behaves:

  • @Retention — SOURCE (discarded by the compiler), CLASS (kept in the class file, the default, but invisible to reflection), or RUNTIME (readable while the program runs).
  • @Target — where it may be used: TYPE, FIELD, METHOD, PARAMETER, TYPE_USE and others.
  • @Documented includes it in Javadoc; @Inherited lets a class annotation pass to subclasses; @Repeatable allows it more than once on the same element.

Reading Annotations at Run Time

This example declares a @Range annotation for fields and a tiny validator that reads it with reflection — the same technique that Jakarta Bean Validation uses for @Min, @Max and @NotNull.

// A custom annotation, kept at run time and read with reflection.
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.List;

@Retention(RetentionPolicy.RUNTIME)      // keep it in the class file and visible to reflection
@Target(ElementType.FIELD)               // allowed only on fields
@interface Range {
    int min() default 0;
    int max();
    String message() default "out of range";
}

class Order {
    @Range(min = 1, max = 100, message = "quantity must be 1..100")
    int quantity;

    @Range(max = 50)
    int discountPercent;

    Order(int quantity, int discountPercent) {
        this.quantity = quantity;
        this.discountPercent = discountPercent;
    }
}

class Validation {
    static List<String> validate(Object target) throws IllegalAccessException {
        List<String> errors = new ArrayList<>();
        for (Field f : target.getClass().getDeclaredFields()) {
            Range r = f.getAnnotation(Range.class);
            if (r == null) continue;
            int value = f.getInt(target);
            if (value < r.min() || value > r.max()) {
                errors.add(f.getName() + "=" + value + ": " + r.message());
            }
        }
        return errors;
    }

    public static void main(String[] args) throws IllegalAccessException {
        System.out.println(validate(new Order(10, 20)));
        System.out.println(validate(new Order(0, 75)));
    }
}

Output:

[]
[quantity=0: quantity must be 1..100, discountPercent=75: out of range]

Without @Retention(RetentionPolicy.RUNTIME), getAnnotation would return null and the validator would silently accept everything — the most common mistake with custom annotations.

Annotations in Practice

Framework Annotations

Most annotations you meet come from libraries. JUnit marks test methods with @Test; Spring wires objects with @Component and @Autowired; JPA maps classes to tables with @Entity and @Id; Lombok generates code at compile time from @Getter. Annotations make such frameworks concise, but the behavior they trigger lives elsewhere: when an annotated program misbehaves, read the documentation of the tool that processes the annotation, not the annotation itself.

Practice

Exercises

  1. Add a @NotBlank annotation for String fields to the validator and test it on a new field.
  2. Change @Range's retention to CLASS, run the program again, and explain the output.
  3. Call the deprecated Legacy.sum from a method without @SuppressWarnings and read the warning that javac -Xlint:all prints.